repo
string
commit
string
message
string
diff
string
gregkh/android-presentation
4c9e19528c1a63794cdf630d29aa864d17d6b86b
image file
diff --git a/images/elchido2.jpg b/images/elchido2.jpg new file mode 100644 index 0000000..9b25797 Binary files /dev/null and b/images/elchido2.jpg differ
gregkh/android-presentation
a1939820c77912edb72251e3df6f0ec669347a92
notes.txt
diff --git a/notes.txt b/notes.txt new file mode 100644 index 0000000..36eb35a --- /dev/null +++ b/notes.txt @@ -0,0 +1,41 @@ +http://elinux.org/Android_Portal +http://elinux.org/Android_Kernel_Features + + +stuff not upstream: + - binder + - ashmem + - pmem + - logger + - wakelocks + - oom notifications + - alarm + - paranoid network security + - timed gpio + + +kernel trees: + android.git.kernel.org + >kernel/common.git + >kernel/experimental.git -> some experimental stuff + >kernel/linux-2.6.git -> supposed to be kernel tree used in android version + >kernel/lk.git -> not a kernel tree, but a bootloader + >kernel/msm.git + >kernel/omap.git -> mirror of kernel tree maintained by texas instruments., supporting OMAP chips. usually based on kernel.org latest version, android products w OMAP chip can use this kernel port. + >kernel/tegra.git -> nvidia kernel tree + + +platform/hardware/alsa_sound.git + ALSA based libaudio, audioflinger + +platform/hardware/broadcom/wlan.git +platform/hardware/htc/dream.git +platform/hardware/libhardware.git hardware abstraction library +platform/hardware/libhardware_legacy.git +platform/hardware/msm7k.git msm7k hardware glue +platform/hardware/qcom/gps.git +platform/hardware/ril.git radio interface layer +platform/hardware/ti/omap3.git +platform/hardware/ti/wlan.git + +
gregkh/android-presentation
4161f5bad46af98fdaed78f81d8ea971d0044045
added .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5664e30 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +git
gregkh/android-presentation
07d9f578969ae09f97d26b9c88678b29cb9b2ab0
title, closing, and disclaimer
diff --git a/android-kernel.odp b/android-kernel.odp new file mode 100644 index 0000000..e2631df Binary files /dev/null and b/android-kernel.odp differ diff --git a/android-kernel.pdf b/android-kernel.pdf new file mode 100644 index 0000000..9e94de0 Binary files /dev/null and b/android-kernel.pdf differ
gregkh/android-presentation
567a3aa3ebffe4e270438da984ded93f4afed57c
add a readme
diff --git a/README b/README new file mode 100644 index 0000000..05bc3c2 --- /dev/null +++ b/README @@ -0,0 +1,3 @@ +This is the presentation that I gave at CELF 2010 +about the Android operating system and how it relates +to the Linux kernel community. diff --git a/foo b/foo deleted file mode 100644 index e69de29..0000000
anarchivist/pybhl
6536f3b02fe4dce1733749ee8a2c4530300966c7
modified gitignore to exclude builddirs etc from setuptools
diff --git a/.gitignore b/.gitignore index 0d20b64..ef5689c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ *.pyc +build +dist +pybhl.egg-info
anarchivist/pybhl
ad587e0eabf206862854619e9995b49dd78ca2b2
alrighty, adding Changes with info
diff --git a/Changes b/Changes index e69de29..6889ca1 100644 --- a/Changes +++ b/Changes @@ -0,0 +1,2 @@ +v0.1 Mon Oct 19 23:16:49 EDT 2009 +- Initial release \ No newline at end of file diff --git a/pybhl/__init__.py b/pybhl/__init__.py index 297742a..e559fdf 100644 --- a/pybhl/__init__.py +++ b/pybhl/__init__.py @@ -1,28 +1,28 @@ # Copyright (C) 2009 Mark A. Matienzo # # This file is part of pybhl, the Python Biodiversity Heritage Library module. # # pybhl 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. # # pybhl 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 pybhl. If not, see <http://www.gnu.org/licenses/>. # __init__.py __version__ = '0.1' -from pybhl import request +from pybhl.request import BHLOpenURLRequest def main(): pass if __name__ == '__main__': main() \ No newline at end of file diff --git a/pybhl/request.py b/pybhl/request.py index 4241b63..7a42025 100644 --- a/pybhl/request.py +++ b/pybhl/request.py @@ -1,60 +1,64 @@ # Copyright (C) 2009 Mark A. Matienzo # # This file is part of pybhl, the Python Biodiversity Heritage Library module. # # pybhl 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. # # pybhl 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 pybhl. If not, see <http://www.gnu.org/licenses/>. # request.py # TODO - ADD OPENURL 1.0 SUPPORT from urllib import urlencode import urllib2 from pybhl.response import BHLResponse VALID_PARAMS = { '0.1': ['title', 'au', 'aulast', 'aufirst', 'publisher', 'date', 'isbn', 'issn', 'coden', 'stitle', 'volume', 'issue', 'spage', 'pid', 'genre'], } class BHLOpenURLRequest(object): # Class to request things via OpenURL using BHL # TODO - Implement a separate module for OpenURL creating/parsing ala # ropenurl for Ruby def __init__(self, format='json', **kwargs): + """Constructor method""" self.baseurl = 'http://www.biodiversitylibrary.org/openurl' self.format = format if self.format == 'json': self.parsing = True else: self.parsing = False self.params = kwargs self.openurl_version = '0.1' def validate(self): + """Simple validator method""" for param in self.params: if param not in VALID_PARAMS[self.openurl_version]: raise ValueError, "Improper parameter for OpenURL version %s"\ % self.openurl_version def create_url(self): + """Generates URL for request to BHL's API""" return self.baseurl + '?format=' + self.format + '&' \ + urlencode(self.params) def get_response(self): + """Get a BHLResponse object based on a created request""" url = self.create_url() rsp = urllib2.urlopen(url).read() return BHLResponse(self, rsp) \ No newline at end of file diff --git a/pybhl/response.py b/pybhl/response.py index b3ff276..b0c971f 100644 --- a/pybhl/response.py +++ b/pybhl/response.py @@ -1,49 +1,51 @@ # Copyright (C) 2009 Mark A. Matienzo # # This file is part of pybhl, the Python Biodiversity Heritage Library module. # # pybhl 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. # # pybhl 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 pybhl. If not, see <http://www.gnu.org/licenses/>. # response.py try: import json # Python >= 2.6 except ImportError: import simplejson as json # otherwise require simplejson from urllib2 import urlopen from BeautifulSoup import BeautifulSoup OCRID = 'ctl00_toolbarContentPlaceHolder_titleVolumeSelectionControl_linkOCR' class BHLResponse(object): - """docstring for BHLResponse""" + """Response class for BHLOpenURLRequests""" def __init__(self, request, data): + """Constructor method""" super(BHLResponse, self).__init__() self.format = request.format if request.parsing is True and request.format == 'json': self.data = json.loads(data) self.parsed = True else: self.data = data self.parsed = False def get_ocr_url(self, index): + """Get the URL containing the OCRed text from archive.org""" if (self.format == 'json') and self.parsed: pageurl = self.data['citations'][index]['Url'] soup = BeautifulSoup(urlopen(pageurl).read()) return soup.find('a', id=OCRID)['href'] else: raise NotImplementedError \ No newline at end of file diff --git a/setup.py b/setup.py index 12d8f69..7218870 100644 --- a/setup.py +++ b/setup.py @@ -1,27 +1,26 @@ from setuptools import setup, find_packages -install_requires = [] +install_requires = ['BeautifulSoup'] classifiers = """ Intended Audience :: Education Intended Audience :: Developers Intended Audience :: Information Technology Intended Audience :: Science/Research License :: OSI Approved :: GNU General Public License (GPL) Programming Language :: Python Development Status :: 3 - Alpha -Topic :: Scientific/Engineering :: Bio-Informatics """ setup( name = 'pybhl', version = '0.1', # remember to update pybhl/__init__.py on release! url = 'http://github.com/anarchivist/pybhl', author = 'Mark A. Matienzo', author_email = '[email protected]', license = 'GPL', packages = find_packages(), install_requires = install_requires, description = 'Interact with the Biodiversity Heritage Library API', classifiers = filter(None, classifiers.split('\n')), )
anarchivist/pybhl
3cca8b1a3a189ad5c635b20264fb362146c32dff
added readme and docstrings throughout; import pybhl will now autoload request.BHLOpenUrlRequest into the pybhl namespace; setup.py tweaks
diff --git a/README b/README new file mode 100644 index 0000000..58c7231 --- /dev/null +++ b/README @@ -0,0 +1,55 @@ +DESCRIPTION +----------- + +pybhl is a Python module that works with the Biodiversity Heritage Library +(BHL) OpenURL-based API to retrieve metadata about material held in the BHL's +online collections. pybhl is loosely based on mjy's rubyBHL (see +http://github.com/mjy/rubyBHL for code, etc.). + +DEPENDENCIES +------------ + +* simplejson or Python >= 2.6 +* BeautifulSoup + + +INSTALLATION +------------ + +You can use easy_install to install the module: + + easy_install pybhl + +If you prefer, you can get the latest version of the source using Git + + git clone git://github.com/anarchivist/pybhl.git + +To install: + + python setup.py install + +USAGE +----- + +>>> import pybhl +>>> b = pybhl.BHLOpenURLRequest(genre='book', title='Manual of North American Diptera', aufirst='Samuel Wendell', aulast='Williston', date='1908', spage='16') +>>> r = b.get_response() +>>> r.data +{u'Status': 1, u'Message': u'', u'citations': [{u'Title': u'Manual of North American Diptera / by Samuel W. Williston.', u'ATitle': u'', u'ItemUrl': u'http://www.biodiversitylibrary.org/item/16772', u'Subjects': [u'Diptera', u'North America', u''], u'PublisherName': u'J.T. Hathaway,', u'Volume': u'', u'Lccn': u'08024896', u'Authors': [u'Williston, Samuel Wendell,'], u'Date': u'1908', u'Pages': u'', u'PublicationFrequency': u'', u'TitleUrl': u'http://www.biodiversitylibrary.org/bibliography/1704', u'Language': u'English', u'Url': u'http://www.biodiversitylibrary.org/page/1316635', u'Issn': u'', u'Genre': u'Book', u'PublisherPlace': u'New Haven :', u'EPage': u'', u'SPage': u'Page 16', u'STitle': u'', u'Isbn': u'', u'Edition': u'3rd ed. ', u'Oclc': u'6445326'}]} +>>> r.get_ocr_url(0) +u'http://www.archive.org/download/manualofnorthame00will/manualofnorthame00will_djvu.txt' + +MORE INFORMATION +---------------- + +Biodiversity Heritage Library +- http://www.biodiversitylibrary.org/ + +BHL's OpenURL Resolver +- http://www.biodiversitylibrary.org/openurlhelp.aspx + +OpenURL 0.1 +- http://alcme.oclc.org/openurl/docs/pdf/openurl-01.pdf + +OpenURL 1.0 +- http://www.niso.org/kst/reports/standards?step=2&project_key=d5320409c5160be4697dc046613f71b9a773cd9e \ No newline at end of file
ernesto-jimenez/charlacampus2010
8f40f8f022d8cbb970006cf3295fc9beff0aec5f
Bazinga demo
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..496ee2c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store \ No newline at end of file diff --git a/bazinga/audio.html b/bazinga/audio.html new file mode 100755 index 0000000..6f32aba --- /dev/null +++ b/bazinga/audio.html @@ -0,0 +1,38 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0"> + <title>Audio demo</title> + <link rel="stylesheet" href="css/master.css" type="text/css" + media="screen"> + <link rel="stylesheet" href="css/portrait.css" type="text/css" + media="screen and (orientation: portrait)"> + <link rel="stylesheet" href="css/landscape.css" type="text/css" + media="screen and (orientation: landscape)"> + <link rel="stylesheet" href="css/iphone.css" type="text/css" + media="only screen and (max-device-width: 480px)"> +</head> +<body> + <div id="container"> + <div id="logo"> + </div> + <div id="button"> + <audio id="bazinga" autobuffer autoloop> + <source src="audio/bazinga.mp3"> + <source src="audio/bazinga.ogg"> + </audio> + <button type="button" id="play">Play</button> + </div> + </div> + <script type="text/javascript"> + document.getElementById('play').onclick = function(event) { + var bazinga = document.getElementById('bazinga'); + var logo = document.getElementById('logo'); + logo.className = "pulsate"; + setTimeout(function () {logo.className = 'steady' }, 500); + bazinga.play(); + } + </script> +</body> +</html> diff --git a/bazinga/audio/bazinga.mp3 b/bazinga/audio/bazinga.mp3 new file mode 100755 index 0000000..558dd95 Binary files /dev/null and b/bazinga/audio/bazinga.mp3 differ diff --git a/bazinga/audio/bazinga.ogg b/bazinga/audio/bazinga.ogg new file mode 100755 index 0000000..61cf506 Binary files /dev/null and b/bazinga/audio/bazinga.ogg differ diff --git a/bazinga/css/iphone.css b/bazinga/css/iphone.css new file mode 100755 index 0000000..eb67f0b --- /dev/null +++ b/bazinga/css/iphone.css @@ -0,0 +1,28 @@ +#button { + text-align: center; + width: 200px; + height: 50px; +} + +@media screen and (orientation: portrait) { + body { + background-color: rgb(130, 29, 35); + } + #logo { + width: 300px; + height: 190px; + -webkit-background-size: 300px 190px; + } +} + +@media screen and (orientation: landscape) { + body { + background-color: rgb(149, 25, 33); + } + #logo { + width: 190px; + height: 190px; + -webkit-background-size: 190px 190px; + float: left; + } +} diff --git a/bazinga/css/landscape.css b/bazinga/css/landscape.css new file mode 100755 index 0000000..a3933db --- /dev/null +++ b/bazinga/css/landscape.css @@ -0,0 +1,14 @@ +body { + background-color: rgb(185,5,31); +} + +#logo { + background-image: url('../images/bazinga-1.jpg'); + width: 410px; + height: 500px; + float: left; + opacity: 0; +} +#button { + float: right; +} diff --git a/bazinga/css/master.css b/bazinga/css/master.css new file mode 100755 index 0000000..7391ecb --- /dev/null +++ b/bazinga/css/master.css @@ -0,0 +1,54 @@ +@-webkit-keyframes pulsate { + 0% { opacity: 0; } + 40% { opacity: 1; } + 60% { opacity: 1; } + 100% { opacity: 0; } +} + +@keyframes pulsate { + 0% { opacity: 0; } + 40% { opacity: 1; } + 60% { opacity: 1; } + 100% { opacity: 0; } +} + +button { + display: inline-block; + background-color: rgb(112,112,112); + background-image: -moz-linear-gradient(100% 100% 90deg, rgb(112,112,112), rgb(184,184,184)); + background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(112,112,112)), to(rgb(184,184,184))); + font-size: 30px; + padding:5px 10px 6px 10px; + font-weight:bold; + text-shadow: 1px 1px 1px rgba(255,255,255,0.5); + border:1px solid rgba(0,0,0,0.4); + -moz-border-radius: 5px; + -moz-box-shadow: 0px 0px 2px rgba(0,0,0,0.5); + -webkit-border-radius: 5px; + -webkit-box-shadow: 0px 0px 2px rgba(0,0,0,0.5); +} + +button:active { + background-image: -moz-linear-gradient(100% 100% 90deg, rgb(184,184,184), rgb(112,112,112)); + background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(184,184,184)), to(rgb(112,112,112))); +} + +#logo.pulsate { + -webkit-animation-name: pulsate; + -webkit-animation-play-state: running; + -webkit-animation-duration: 0.5s; + -webkit-animation-iteration-count: infinite; + -webkit-animation-timing-function: ease-in-out; + + animation-name: pulsate; + animation-play-state: running; + animation-duration: 0.5s; + animation-iteration-count: infinite; + animation-timing-function: ease-in-out; +} + +#logo.steady { + -webkit-animation-play-state: paused; + + animation-play-state: paused; +} diff --git a/bazinga/css/portrait.css b/bazinga/css/portrait.css new file mode 100755 index 0000000..c973b99 --- /dev/null +++ b/bazinga/css/portrait.css @@ -0,0 +1,14 @@ +body { + background-color: rgb(165,25,38); +} + +#logo { + background-image: url('../images/bazinga.jpg'); + width: 500px; + height: 270px; + float: none; + opacity: 0; +} +#button { + float: none; +} diff --git a/bazinga/images/bazinga-1.jpg b/bazinga/images/bazinga-1.jpg new file mode 100755 index 0000000..cdd684a Binary files /dev/null and b/bazinga/images/bazinga-1.jpg differ diff --git a/bazinga/images/bazinga.jpg b/bazinga/images/bazinga.jpg new file mode 100755 index 0000000..9a9aef9 Binary files /dev/null and b/bazinga/images/bazinga.jpg differ
koush/android_vendor_samsung_epic
c04b313c32f6ed21188dd922d65f14660d5ba914
initial
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/AndroidBoard.mk b/AndroidBoard.mk new file mode 100644 index 0000000..3afcf49 --- /dev/null +++ b/AndroidBoard.mk @@ -0,0 +1,20 @@ +LOCAL_PATH := $(call my-dir) + +ifeq ($(TARGET_PREBUILT_KERNEL),) +TARGET_PREBUILT_KERNEL := $(LOCAL_PATH)/kernel +endif + +file := $(INSTALLED_KERNEL_TARGET) +ALL_PREBUILT += $(file) +$(file): $(TARGET_PREBUILT_KERNEL) | $(ACP) + $(transform-prebuilt-to-target) + +file := $(TARGET_ROOT_OUT)/init.smdkc110.rc +ALL_PREBUILT += $(file) +$(file) : $(LOCAL_PATH)/init.smdkc110.rc | $(ACP) + $(transform-prebuilt-to-target) + +file := $(TARGET_RECOVERY_ROOT_OUT)/sbin/postrecoveryboot.sh +ALL_PREBUILT += $(file) +$(file) : $(LOCAL_PATH)/postrecoveryboot.sh | $(ACP) + $(transform-prebuilt-to-target) diff --git a/BoardConfig.mk b/BoardConfig.mk new file mode 100644 index 0000000..2e7a615 --- /dev/null +++ b/BoardConfig.mk @@ -0,0 +1,36 @@ +# +# Product-specific compile-time definitions. +# + +TARGET_BOARD_PLATFORM := intrinsity +TARGET_CPU_ABI := armeabi + +TARGET_NO_BOOTLOADER := true + +TARGET_BOOTLOADER_BOARD_NAME := galaxys + +BOARD_KERNEL_CMDLINE := no_console_suspend=1 console=null +BOARD_KERNEL_BASE := 0x02e00000 + +BOARD_BOOTIMAGE_MAX_SIZE := $(call image-size-from-data-size,0x00280000) +BOARD_RECOVERYIMAGE_MAX_SIZE := $(call image-size-from-data-size,0x00500000) +BOARD_SYSTEMIMAGE_MAX_SIZE := $(call image-size-from-data-size,0x07500000) +BOARD_USERDATAIMAGE_MAX_SIZE := $(call image-size-from-data-size,0x04ac0000) +# The size of a block that can be marked bad. +BOARD_FLASH_BLOCK_SIZE := 131072 + +BOARD_HAS_NO_SELECT_BUTTON := true +BOARD_HAS_NO_MISC_PARTITION := true +BOARD_USES_FFORMAT := true +BOARD_RECOVERY_IGNORE_BOOTABLES := true + +BOARD_DATA_DEVICE := /dev/block/stl10 +BOARD_DATA_FILESYSTEM := auto +BOARD_DATA_FILESYSTEM_OPTIONS := llw,check=no,nosuid,nodev +BOARD_SYSTEM_DEVICE := /dev/block/stl9 +BOARD_SYSTEM_FILESYSTEM := auto +BOARD_SYSTEM_FILESYSTEM_OPTIONS := llw,check=no +BOARD_CACHE_DEVICE := /dev/block/stl11 +BOARD_CACHE_FILESYSTEM := auto +BOARD_CACHE_FILESYSTEM_OPTIONS := llw,check=no,nosuid,nodev +BOARD_CUSTOM_RECOVERY_KEYMAPPING := ../../vendor/samsung/epic/default_recovery_ui.c \ No newline at end of file diff --git a/default_recovery_ui.c b/default_recovery_ui.c new file mode 100644 index 0000000..17c9fd2 --- /dev/null +++ b/default_recovery_ui.c @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <linux/input.h> + +#include "recovery_ui.h" +#include "common.h" +#include "extendedcommands.h" + +char* MENU_HEADERS[] = { NULL }; + +char* MENU_ITEMS[] = { "reboot system now", + "apply sdcard:update.zip", + "wipe data/factory reset", + "wipe cache partition", + "install zip from sdcard", + "backup and restore", + "mounts and storage", + "advanced", + NULL }; + +int device_toggle_display(volatile char* key_pressed, int key_code) { + int alt = key_pressed[KEY_LEFTALT] || key_pressed[KEY_RIGHTALT]; + if (alt && key_code == KEY_L) + return 1; + // allow toggling of the display if the correct key is pressed, and the display toggle is allowed or the display is currently off + if (ui_get_showing_back_button()) { + return get_allow_toggle_display() && (key_code == KEY_HOME || key_code == KEY_MENU || key_code == KEY_END); + } + return get_allow_toggle_display() && (key_code == KEY_HOME || key_code == KEY_MENU || key_code == KEY_POWER || key_code == KEY_END); +} + +int device_reboot_now(volatile char* key_pressed, int key_code) { + return 0; +} + +int device_handle_key(int key_code, int visible) { + if (visible) { + switch (key_code) { + case 49: + case 52: + return HIGHLIGHT_DOWN; + + case 39: + case 51: + return HIGHLIGHT_UP; + + case 40: + case 46: + return SELECT_ITEM; + + case 58: + case 102: + if (!get_allow_toggle_display()) + return GO_BACK; + } + } + + return NO_ACTION; +} + +int device_perform_action(int which) { + return which; +} + +int device_wipe_data() { + return 0; +} diff --git a/device_epic.mk b/device_epic.mk new file mode 100644 index 0000000..a168ebc --- /dev/null +++ b/device_epic.mk @@ -0,0 +1,23 @@ +# +# Copyright (C) 2009 The Android Open-Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# To be included directly by a device_magic_*.mk makefile; +# do not use inherit-product on this file. + +DEVICE_PACKAGE_OVERLAYS := vendor/htc/magic/overlay vendor/htc/common-open/overlay + +PRODUCT_PACKAGES += \ + FieldTest diff --git a/init.smdkc110.rc b/init.smdkc110.rc new file mode 100644 index 0000000..e1be5d9 --- /dev/null +++ b/init.smdkc110.rc @@ -0,0 +1,16 @@ +on boot +# setprop net.eth0.dns1 10.32.192.11 +# setprop net.eth0.dns2 10.32.193.11 + setprop ro.build.product smdkc110 + setprop ro.product.device smdkc110 + setprop ro.radio.noril yes + +# fake some battery state + setprop status.battery.state Slow + setprop status.battery.level 5 + setprop status.battery.level_raw 50 + setprop status.battery.level_scale 9 + +service smdkc110-setup /system/etc/init.smdkc110.sh + oneshot + diff --git a/kernel b/kernel new file mode 100644 index 0000000..bcd781c Binary files /dev/null and b/kernel differ diff --git a/postrecoveryboot.sh b/postrecoveryboot.sh new file mode 100755 index 0000000..33f07a5 --- /dev/null +++ b/postrecoveryboot.sh @@ -0,0 +1,5 @@ +#!/sbin/sh +rm -f /etc +mkdir -p /etc +mkdir -p /datadata +chmod 4777 /sbin/su diff --git a/system.prop b/system.prop new file mode 100644 index 0000000..f8f0a85 --- /dev/null +++ b/system.prop @@ -0,0 +1,8 @@ +# +# system.prop for smdkc110 +# + +rild.libpath=/system/lib/libreference-ril.so +rild.libargs=-d /dev/ttyS0 +ro.sf.lcd_density=240 +persist.sys.timezone=America/New_York
kozo/LogicalDeleteBehavior
ac1fce8e4e62d0e382e5399bc0e795046efb1099
初回
diff --git a/models/behaviors/logical_delete.php b/models/behaviors/logical_delete.php new file mode 100644 index 0000000..cfa1154 --- /dev/null +++ b/models/behaviors/logical_delete.php @@ -0,0 +1,119 @@ +<?php +class LogicalDeleteBehavior extends ModelBehavior { + var $settings = array(); + + //------------------------------------------------------------- + // それぞれのモデルで上書きできるメンバ変数 + //------------------------------------------------------------- + // delete flagのカラム名 + private $deleteFlagName = 'delete_flag'; + // deleteフラグをfind時にチェックするか(true:チェックする、false:チェックしない) + private $isDeleteFlag = true; + //------------------------------------------------------------- + + function setup(&$model, $config = array()) { + $this->settings = $config; + } + + /** + * find前処理 + * + * @access public + * @author saku + */ + function beforeFind(&$model, $query){ + // findにdelete flagを自動で付加する + $query = $this->_findDeleteFlag($model, $query); + + return $query; + } + + + /** + * 削除前処理 + * + * @access public + * @author saku + */ + function beforeDelete(&$model, $cascade = true) + { + if(isset($model->isDeleteFlag) && is_bool($model->isDeleteFlag)){ + // フラグの変更 + $this->isDeleteFlag = $model->isDeleteFlag; + } + + if($this->isDeleteFlag === true){ + // 論理削除実行 + $this->_logicalDelete($model); + return false; + }else{ + // 物理削除実行 + return true; + } + } + + /** + * findの検索条件に自動的にDeleteフラグを設定する + * + * @access private + * @author saku + */ + private function _findDeleteFlag(&$model, $query){ + if(isset($model->isDeleteFlag) && is_bool($model->isDeleteFlag)){ + $this->isDeleteFlag = $model->isDeleteFlag; + } + if($this->isDeleteFlag === false){ + return $query; + } + + $modelName = $model->name; + if(isset($model->deleteFlagName)){ + // delete flagのカラム名の変更 + $this->deleteFlagName = $model->deleteFlagName; + } + + // 論理削除カラム名 + $name = sprintf("%s.%s", $modelName, $this->deleteFlagName); + + if(empty($query['conditions'])){ + // conditionsに何も設定されていない + $query['conditions'] = array($name => false); + }else if(is_array($query['conditions'])){ + // conditions が配列で書かれている + $bufCond = $query['conditions']; + $deleteConditions = array($name=>false); + $query['conditions'] = Set::merge($bufCond, $deleteConditions); + }else if(is_string($query['conditions'])){ + // conditions が文字列で書かれている + $bufCond = $query['conditions']; + $query['conditions'] = array($name=>false, $bufCond); + }else{ + // とりあえず何もない? + } + + return $query; + } + + /** + * deleteフラグを立てる + * ※コールバック呼ばれない + * + * @access private + * @author saku + */ + private function _logicalDelete(&$model){ + if(empty($model->id) || !is_numeric($model->id)){ + return false; + } + + if(isset($model->deleteFlagName)){ + // delete flagのカラム名の変更 + $this->deleteFlagName = $model->deleteFlagName; + } + + $model->saveField($this->deleteFlagName, true, array('callbacks'=>false)); + + return true; + } +} +?> \ No newline at end of file
vim-scripts/fvl.vim
bb9e7773d04c54198bb6513ccbf48589b7154d2d
Version 1.0: Initial upload
diff --git a/README b/README new file mode 100644 index 0000000..e5ba42b --- /dev/null +++ b/README @@ -0,0 +1,24 @@ +This is a mirror of http://www.vim.org/scripts/script.php?script_id=903 + +Fred's Vim Lisp + +This plugin allows you to run a Lisp interpreter in a Vim window and send Lisp expressions to it. You can send selected lines, a [count] number of lines, or a range of lines. + +fvl.vim defines a handful of commands: + LispOpen opens the lisp window and starts the lisp interpreter + LispClose close the lisp window and terminate lisp. This happens automatically when the lisp buffer is closed. + LispRefresh try and read from lisp when your in a pinch. + LispDo like perldo. Evaluate a lisp expression. You MUST escape quotes. + LispCount evaluate [count] lines. + LispRange evaluate a range of lines. + +In practice, all you need to remember is LispDo and possibly LispRange. +I've added the following mapping to my .vimrc file: + +map <C-L> :LispRange + +That map allows you to hit <C-L> to send a single line to the lisp interpreter, or select a few lines and send them all together. + + +NOTE: There is already another script that does similar things to fvl.vim, vimscript #221 (VIlisp.vim). What's the difference? Mostly, fvl.vim requires only one file (the plugin file) to work and is a bit easier to setup (imho). + diff --git a/plugin/fvl.vim b/plugin/fvl.vim new file mode 100644 index 0000000..0714444 --- /dev/null +++ b/plugin/fvl.vim @@ -0,0 +1,232 @@ +" fvl.vim Copyright 2003 Ray Wallace III +" +" This program is free software; you can redistribute it and/or +" modify it under the terms of the GNU General Public +" License as published by the Free Software Foundation; either +" version 2 of the License, or (at your option) any later version. +" +" This program is distributed in the hope that it will be useful, +" but WITHOUT ANY WARRANTY; without even the implied warranty of +" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +" General Public License for more details. +" +" You should have received a copy of the GNU Library General Public +" License along with this library; if not, write to the +" Free Software Foundation, Inc., 59 Temple Place - Suite 330, +" Boston, MA 02111-1307, USA. + +" What we do: +" Use the Expect module to spawn the interpreter indicated by $LispInterp and +" create pipes for it. When the user wants to run some lisp (via LispDo, +" LispCount, or LispRange), write it out the pipe and the use expect() to read +" output from the interpreter until it prints the prompt defined by +" $LispPrompt. +" +" This plugin most likely works not just for lisp interpreters, but for any +" program that has a read-evaluate loop and prints a predictable prompt. +" +" LispOpen Opens the Lisp Window +" LispClose Closes same and shuts down Lisp +" LispRefresh Try to read more from Lisp +" LispDo Works like perldo. You MUST escape quotes. ex: +" :LispDo (print \"hello\") +" LispCount Evaluate [count] lines +" LispRange Evaluate [range] lines +" + +" REQUIREMENTS: +" perl5 +" perl Expect module (# cpan Expect) +" vim (compiled with +perl, +windows might be needed also) +" gcl or clisp (possibly any lisp interp) +" + +"---------------------------------- +" Site configurable variables follow +"---------------------------------- + +perl <<EOF + +$LispInterp = "clisp"; # This is the name of the lisp interpreter + # that will be used. +$LispPrompt = "^.*\\[\\d+\\]>"; # This here's a regular expression that + # matches your lisp's prompt. This one matches + # CLisp. +$LispTimeout = 10; # How long until an attempt to read from lisp + # will timeout, in seconds. +$JumpToLisp = 1; # If this is true, then jump to the window + # containing the lisp interpreter after every + # lisp command. +$DefaultWindowSize = 15; # The initial height of the Lisp window. + +EOF + +"---------------------------------- +" End site configurable variables +"---------------------------------- + +" Globals +perl <<EOF +use Expect; + +$Buffer; +$Window; +$Pipe; + +EOF + +" Talking to Lisp +perl <<EOF + +sub readFromLisp(){ + my $done; + + if($Buffer && $Pipe){ + # read until we find a line that matches $LispPrompt, then put all the + # text that came before the prompt into $text. + my @ret = $Pipe->expect($LispTimeout, '-re', $LispPrompt); + my $text = $Pipe->exp_before(); + + # for whatever reason, newlines come across as null characters, so replace + # them with the newline. + $text =~ tr/\0x0/\n/; + + $Buffer->Append($Buffer->Count(), split(/\n/, $text)); + $Buffer->Append($Buffer->Count(), "> ") + if !$ret[1]; + + $_ = $Buffer->Count(); + VIM::Windows($Window)->Cursor($_, length($Buffer->Get($_))); + if($JumpToLisp){ + VIM::DoCommand($Window."wincmd w"); + # Vim seems to queue up all the commands to execute at once so that + # we only get the _net-effect_ of all of the commands. So, if we do + # the command below, then the command above doesn't get done, so the + # lisp window doesn't scroll. +# VIM::DoCommand("wincmd p"); + } + } + else{ + VIM::Msg("Lisp buffer or pipe isn't open!", "Error"); + } +} + +sub writeToLisp(@){ + my $text = "@_"; + + if(!$Pipe){ + initLispBuffer(); + } + + if($Buffer && $Pipe){ + $text = $text."\n" if($text !~ /^.*\n$/); + + $Pipe->send($text); + $_ = $Buffer->Count(); + $Buffer->Append($Buffer->Count(), split(/\n/, $text)); + + # Catch up with what lisp has to say + readFromLisp(); + } + else{ + VIM::Msg("Lisp buffer isn't open!", "Error"); + } +} + +sub writeCountToLisp($){ + my @cursor = $curwin->Cursor(); + + writeToLisp($curBuf->Get($cursor[0] .. $cursor[0] + $_[0])); +} + +sub writeRangeToLisp($$){ + my ($first, $second) = @_; + +# die "$first .. $second \n"; + writeToLisp($curbuf->Get($first .. $second)); +} + +EOF + +" Starting up Lisp +perl <<EOF + +sub setupWindow(){ + my $winNum = 0; + + # make a new window with the file "Lisp.Interpreter", then disable saving + # the file, disable its swap file, and turn on lisp syntax highlighting. + VIM::DoCommand($DefaultWindowSize."split +e Lisp.Interpreter"); + VIM::DoCommand("setlocal buftype=nofile noswapfile filetype=lisp"); + + $Buffer = VIM::Buffers("Lisp.Interpreter") + or die "Couldn't Create the Lisp buffer!\n"; + $Buffer->Append(0, "Faboo's Lisp Wrapper"); + + # figure out what window Vim put our buffer in. + foreach (VIM::Windows()){ + ++$winNum; + $Window = $winNum if $_->Buffer()->Name() eq "Lisp.Interpreter"; + } + +# VIM::DoCommand("let g:window = $Window"); +} + +sub startLisp($){ + my $lisp = $_[0]; + my $pid; + + # create a new expect object, change its behavior to be pipe-like and + # disable the echoing of lisp's output to the terminal, then fork/exec the + # lisp interpreter. + $Pipe = new Expect(); + $Pipe->raw_pty(1); + $Pipe->log_stdout(0); + $Pipe->spawn($lisp) or die "Couldn't run Lisp\n"; + + print "Lisp is running\n"; +} + +sub initLispBuffer(){ + $" = "\n"; + + unless($Pipe){ + setupWindow(); + startLisp($LispInterp); + readFromLisp(); + } +} + +EOF + +" Tearing Lisp down +perl <<EOF + +sub closeLisp(){ + print "Exiting Lisp\n"; + $Pipe->send("(exit)"); + + undef $Pipe; +} + +sub closeLispBuffer(){ + my $bufNum = $Buffer->Number(); + + VIM::DoCommand("bd $bufNum"); +} + +EOF + +autocmd BufDelete Lisp.Interpreter perl closeLisp() + +command! -nargs=0 -bar LOpen perl initLispBuffer() +command! -nargs=0 -bar LispOpen perl initLispBuffer() +command! -nargs=0 -bar LClose perl closeLispBuffer() +command! -nargs=0 -bar LispClose perl closeLispBuffer() +command! -nargs=0 -bar LRefresh perl readFromLisp() +command! -nargs=0 -bar LispRefresh perl readFromLisp() + +command! -nargs=* -bar LispDo perl writeToLisp(q!<args>!) +command! -nargs=0 -bar -count=0 LispCount perl writeCountToLisp(<count>) +command! -nargs=0 -bar -range LispRange perl writeRangeToLisp(<line1>, <line2>) +
agrimm/theweatherinlondon
5864dd09f62a3beec776a5d22f8f7f30f96736c1
Adjusted deployment options.
diff --git a/config/deploy.example.rb b/config/deploy.example.rb index f99e886..e4873ad 100644 --- a/config/deploy.example.rb +++ b/config/deploy.example.rb @@ -1,35 +1,38 @@ #require 'mongrel_cluster/recipes' -set :application, "weatherinlondon" +set :use_sudo, false + +set :application, "mayweather" set :repository, "[email protected]:agrimm/theweatherinlondon.git" default_run_options[:pty] = true set :branch, "master" set :user, "sample_user_name" +raise "Forgot to set user name" if "#{user}" == "example_user_name" # If you aren't deploying to /u/apps/#{application} on the target # servers (which is the default), you can specify the actual location # via the :deploy_to variable: -set :deploy_to, "/home/#{user}/#{application}" +set :deploy_to, "/home/#{user}/etc/rails_apps/#{application}" set :deploy_via, :copy # If you aren't using Subversion to manage your source code, specify # your SCM below: set :scm, :git #No mongrel cluster available #set :mongrel_conf, "#{current_path}/config/mongrel_cluster.yml" set :symlink_commands, "ln -nfs #{deploy_to}/#{shared_dir}/config/database.yml #{release_path}/config/database.yml" role :app, "theweatherinlondon.com" role :web, "theweatherinlondon.com" role :db, "theweatherinlondon.com", :primary => true #Courtesy of paulhammond.org and also pragmatic deployment, how to deal with database.yml and friends desc "link in production database credentials, and other similar files" task :after_update_code do run "#{symlink_commands}" end
agrimm/theweatherinlondon
99376742745e628753ac7830301c3b14b108b59d
Ignore deploy.rb
diff --git a/config/.gitignore b/config/.gitignore index b5649dd..41d5104 100644 --- a/config/.gitignore +++ b/config/.gitignore @@ -1 +1,2 @@ database.yml +deploy.rb
agrimm/theweatherinlondon
8e83701e8ca43cca6b7cc8ee6178f35778e6ab29
Reinstated instruction to clean results of duplicates.
diff --git a/app/models/article.rb b/app/models/article.rb index 98aa675..d61efe7 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,253 +1,254 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end phrase = Phrase.build_from_document(@parsed_document_text) @words = phrase.words @errors = find_errors raise(ArgumentError, @errors.first) unless @errors.empty? end def find_errors errors = [] errors << "Document has too many words" if has_too_many_words? errors << "Document has too few words" if has_too_few_words? errors end def has_too_few_words? return (word_count < 2) end def has_too_many_words? return (word_count > Repository.maximum_allowed_document_size) end def word_count @words.size end #Read in a document, and return an array of phrases and their matching articles def parse parse_results = [] @words.each_index do |i| i.upto(@words.size - 1) do |j| phrase = Phrase.new(@words[i..j]) unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) break unless @repository.try_this_phrase_or_longer?(phrase) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase.to_s, matching_article] end end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) phrase_string = phrase.to_s #return false #This causes unit tests to fail #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase_string.chars.downcase)} #Unicode safe, too slow? :( return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase_string.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end #a method to get rid of the duplicate results def clean_results(parse_results, existing_article_titles) + parse_results.uniq! cleaned_results = clean_results_of_partial_phrases(parse_results) cleaned_results = clean_results_of_redirects_to_detected_articles(cleaned_results) cleaned_results = clean_results_of_redirects_to_wikified_titles(cleaned_results, existing_article_titles) cleaned_results end #Get rid of results with a phrase shorter than another phrase in parse_results def clean_results_of_partial_phrases(results) cleaned_results = [] results.each do |current_result| current_result_phrase = current_result[0] cleaned_results << current_result unless results.any? do |other_result| other_result_phrase = other_result[0] is_a_partial_string?(other_result_phrase, current_result_phrase) end end cleaned_results end #is potentially_partial_string a substring of (but not the whole of) containing_string? def is_a_partial_string?(containing_string, potentially_partial_string) return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) ) end def clean_results_of_redirects_to_detected_articles(results) results.delete_if do |phrase, matching_article| results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end results end def clean_results_of_redirects_to_wikified_titles(results, existing_article_titles) results.delete_if do |phrase, matching_article| (matching_article.redirect_target and existing_article_titles.any? {|article_title| matching_article.redirect_target.title.downcase == article_title.downcase}) #Not unicode safe? end results end end #A phrase made up of words class Phrase attr_reader :words def initialize(words) @words = words @phrase = words.join(" ") end def to_s @phrase end def self.build_from_document(document) words = document.split(/[[:space:],.""'']+/) phrase = Phrase.new(words) end end
agrimm/theweatherinlondon
c4df76182d232d6b752bf4b17e3c50dcf269f128
Refactored code a bit
diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index 18fa2d7..1affbe7 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,47 +1,56 @@ class ReadController < ApplicationController def read @repository_choices = Repository.find(:all).map {|rc| [rc.short_description, rc.id]} - @default_repository_choice = params[:repository_id].to_i - if params[:repository_id].nil? - hard_wired_preference = "English language Wikipedia" - @repository_choices.each do |short_description, id_number| - if short_description == hard_wired_preference - @default_repository_choice = id_number - end - end - end + @default_repository_choice = determine_default_repository_choice @markup_choices = [ ["Auto-detect (default)", "auto-detect"], ["MediaWiki formatting", "mediawiki"], ["Plain text", "plain"] ] if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end repository = Repository.find(params[:repository_id]) unless repository @errors << "Can't find repository" end markup = params[:markup] unless @markup_choices.map{|pair| pair.last}.include?(markup) @errors << "Invalid markup choice" end if @errors.empty? begin document = Article.new_document(document_text, repository, markup) @parse_results = document.parse rescue ArgumentError => error if error.message == "Document has too many words" @errors << "Please submit a text fewer than #{Repository.maximum_allowed_document_size} words long" elsif error.message == "Document has too few words" @errors << "Please submit a text with at least two words in it" else raise end end end end end + private + def determine_default_repository_choice + unless params[:repository_id].nil? + default_repository_choice = params[:repository_id].to_i + else params[:repository_id].nil? + hard_wired_preference = "English language Wikipedia" + @repository_choices.each do |short_description, id_number| + if short_description == hard_wired_preference + default_repository_choice = id_number + end + end + end + return default_repository_choice + end + + + end diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index 1fb6bf9..b721525 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,51 +1,53 @@ <% unless @errors.blank? %> + <H1>Errors with input</H1> + <p>The following errors were found:</p> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> <p>(Maximum <%= Repository.maximum_allowed_document_size %> words)</p> <% form_tag(:action => :read) do %> <table> <tr><td colspan=2> <%= text_area_tag(:document_text, h(params[:document_text]), :cols=> 80, :rows=> 10) %></td></tr> <tr><td>Web site:</td> <td><%= select_tag(:repository_id, options_for_select(@repository_choices, @default_repository_choice) )%></td></tr> <tr><td>Markup (if any)</td> <td><%= select_tag "markup", options_for_select(@markup_choices) %></td></tr> <tr><td> <%= submit_tag("Submit text") %> </td><td></td></tr> </table> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %> <H2>How to use The Weather in London</H2> <p>The Weather in London provides a different kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> <p>For example, if you submitted <a href="http://en.wikinews.org/wiki/Last_Titan_launch_complex_at_Cape_Canaveral_demolished">this block of text</a></p> <blockquote>Launch Complex 40 (LC-40) at the Cape Canaveral Air Force Station, Merritt Island, Florida has been demolished. The Mobile Service Structure (MSS), which was once used to load payloads onto Titan III and Titan IV rockets, was toppled by explosive charges at 13:00 GMT.</blockquote> <p>you would discover that Wikipedia has articles on Launch Complex, Cape Canaveral Air Force Station, Merritt Island, Titan III and Titan IV.</p> <p>You can also choose to see if a block of text contains a person or electorate in the <a href="http://en.wikipedia.org/wiki/Australian_House_of_Representatives">Australian House of Representatives</a>. This is possibly of marginal utility, but is an example of this concept not just applying for wikis.</p> <p>Currently, only phrases with more than one non-trivial word are checked, rather than single words, to reduce clutter.</p>
agrimm/theweatherinlondon
0a881b71868608e59582ed94c72448dd0b1dc7d2
Added error notification if the text is too small.
diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index 790c4c9..18fa2d7 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,45 +1,47 @@ class ReadController < ApplicationController def read @repository_choices = Repository.find(:all).map {|rc| [rc.short_description, rc.id]} @default_repository_choice = params[:repository_id].to_i if params[:repository_id].nil? hard_wired_preference = "English language Wikipedia" @repository_choices.each do |short_description, id_number| if short_description == hard_wired_preference @default_repository_choice = id_number end end end @markup_choices = [ ["Auto-detect (default)", "auto-detect"], ["MediaWiki formatting", "mediawiki"], ["Plain text", "plain"] ] if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end repository = Repository.find(params[:repository_id]) unless repository @errors << "Can't find repository" end markup = params[:markup] unless @markup_choices.map{|pair| pair.last}.include?(markup) @errors << "Invalid markup choice" end if @errors.empty? begin document = Article.new_document(document_text, repository, markup) @parse_results = document.parse rescue ArgumentError => error if error.message == "Document has too many words" @errors << "Please submit a text fewer than #{Repository.maximum_allowed_document_size} words long" + elsif error.message == "Document has too few words" + @errors << "Please submit a text with at least two words in it" else raise end end end end end end diff --git a/app/models/article.rb b/app/models/article.rb index 3043ab4..98aa675 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,233 +1,253 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end phrase = Phrase.build_from_document(@parsed_document_text) @words = phrase.words - raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size + @errors = find_errors + raise(ArgumentError, @errors.first) unless @errors.empty? + end + + def find_errors + errors = [] + errors << "Document has too many words" if has_too_many_words? + errors << "Document has too few words" if has_too_few_words? + errors + end + + def has_too_few_words? + return (word_count < 2) + end + + def has_too_many_words? + return (word_count > Repository.maximum_allowed_document_size) + end + + def word_count + @words.size end #Read in a document, and return an array of phrases and their matching articles def parse parse_results = [] @words.each_index do |i| i.upto(@words.size - 1) do |j| phrase = Phrase.new(@words[i..j]) unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) break unless @repository.try_this_phrase_or_longer?(phrase) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase.to_s, matching_article] end end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) phrase_string = phrase.to_s #return false #This causes unit tests to fail #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase_string.chars.downcase)} #Unicode safe, too slow? :( return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase_string.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end #a method to get rid of the duplicate results def clean_results(parse_results, existing_article_titles) cleaned_results = clean_results_of_partial_phrases(parse_results) cleaned_results = clean_results_of_redirects_to_detected_articles(cleaned_results) cleaned_results = clean_results_of_redirects_to_wikified_titles(cleaned_results, existing_article_titles) cleaned_results end #Get rid of results with a phrase shorter than another phrase in parse_results def clean_results_of_partial_phrases(results) cleaned_results = [] results.each do |current_result| current_result_phrase = current_result[0] cleaned_results << current_result unless results.any? do |other_result| other_result_phrase = other_result[0] is_a_partial_string?(other_result_phrase, current_result_phrase) end end cleaned_results end #is potentially_partial_string a substring of (but not the whole of) containing_string? def is_a_partial_string?(containing_string, potentially_partial_string) return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) ) end def clean_results_of_redirects_to_detected_articles(results) results.delete_if do |phrase, matching_article| results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end results end def clean_results_of_redirects_to_wikified_titles(results, existing_article_titles) results.delete_if do |phrase, matching_article| (matching_article.redirect_target and existing_article_titles.any? {|article_title| matching_article.redirect_target.title.downcase == article_title.downcase}) #Not unicode safe? end results end end #A phrase made up of words class Phrase attr_reader :words def initialize(words) @words = words @phrase = words.join(" ") end def to_s @phrase end def self.build_from_document(document) words = document.split(/[[:space:],.""'']+/) phrase = Phrase.new(words) end end diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index c5afea4..01d6c6d 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,233 +1,250 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories fixtures :redirects def setup - @empty_document = Document.new("", Repository.find(:first), "auto-detect") + @empty_document = Document.new("Empty meaningless content", Repository.find(:first), "auto-detect") @af_uncyclopedia = Repository.find_by_abbreviation("af-uncyclopedia") @auto_detect = "auto-detect" end #The tests in this method may not make sense right now def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| if rand < 0.04 syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) #Don't remove the inside text parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option else #Remove the inside text parsed_text = pre_syntax_option + post_syntax_option end syntax_test_pairs << [unparsed_text, parsed_text] end end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] assert_equal parsed_text, @empty_document.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" assert_equal ["London"], @empty_document.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" assert_equal "abc mno", @empty_document.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| assert_equal "start finish", @empty_document.parse_non_direct_links(wiki_text) assert_equal "start finish", @empty_document.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text - document_text = "[[en:Wikipedia]]" + document_text = "[[en:Wikipedia]] meaningless text" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] results = parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end #Test whether the parser can handle non-ASCII text def test_non_ascii_text repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] phrases.each do |phrase| document_text = phrase results = parse_text_document(document_text, repository, markup) assert_equal 1, results.size, "Problem parsing #{phrase}" end end def test_redirect_target_and_sources misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") assert_equal correct_article, misspelled_article.redirect_target assert_not_equal unrelated_article, misspelled_article.redirect_target assert_nil correct_article.redirect_target assert_equal [misspelled_article], correct_article.redirect_sources assert_not_equal [unrelated_article], correct_article.redirect_sources assert_equal [], misspelled_article.redirect_sources end #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results def test_redirect_cleaning repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") document_text_results_pairs = [] document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] #Just checking the misspelled article exists document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] #Just checking the correctly spelled article exists document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] #If both are unwikified, assert only the correct spelling is wikified document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #If the correct spelling is wikified, don't wikify the incorrect spelling document_text_results_pairs.each do |document_text, expected_results| actual_results = parse_text_document(document_text, repository, markup) assert_equal expected_results, actual_results end end #Given a wikified singular, and an unwikified plural, assert that the plural is not detected as a result #This test is identical to test_redirect_cleaning except it uses lower cases def test_detect_redirected_plurals document_text = "a [[running back]] amongst running backs" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results, "Problem with redirects" end def test_handles_articles_without_redirect_targets maria_theresa_article = Article.find_by_title("Maria Theresa of Austria") document_text = "a [[running back]] amongst running backs was #{maria_theresa_article.title}" expected_results = [ [maria_theresa_article.title, maria_theresa_article] ] actual_results = nil assert_nothing_raised do actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) end assert_equal expected_results, actual_results end def test_handles_underscores_in_wikified_text document_text = "I wish to underscore the fact that a [[running_back]] is a running back no matter what." expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results end def parse_text_document(document_text, repository, markup) document = Article.new_document(document_text, repository, markup) return document.parse end def test_ignore_boring_phrases document_text = "the the the the the the" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results end + def test_reject_too_many_words + maximum_words = Repository.maximum_allowed_document_size + too_big_document = "foo " * (maximum_words + 1) + assert_raise(ArgumentError) do + parse_text_document(too_big_document, @af_uncyclopedia, @auto_detect) + end + end + + def test_reject_too_few_words + too_small_documents = ["", "foo "] + too_small_documents.each do |too_small_document| + assert_raise(ArgumentError) do + parse_text_document(too_small_document, @af_uncyclopedia, @auto_detect) + end + end + end + end
agrimm/theweatherinlondon
6a0cf312a9f8f3d0225d69a1bdbf5ed851454ca8
Fixed ugly line of code.
diff --git a/app/models/article.rb b/app/models/article.rb index d8470c8..3043ab4 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,233 +1,233 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end phrase = Phrase.build_from_document(@parsed_document_text) @words = phrase.words raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles def parse parse_results = [] - 0.upto(@words.size - 1) do |i| + @words.each_index do |i| i.upto(@words.size - 1) do |j| phrase = Phrase.new(@words[i..j]) unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) break unless @repository.try_this_phrase_or_longer?(phrase) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase.to_s, matching_article] end end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) phrase_string = phrase.to_s #return false #This causes unit tests to fail #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase_string.chars.downcase)} #Unicode safe, too slow? :( return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase_string.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end #a method to get rid of the duplicate results def clean_results(parse_results, existing_article_titles) cleaned_results = clean_results_of_partial_phrases(parse_results) cleaned_results = clean_results_of_redirects_to_detected_articles(cleaned_results) cleaned_results = clean_results_of_redirects_to_wikified_titles(cleaned_results, existing_article_titles) cleaned_results end #Get rid of results with a phrase shorter than another phrase in parse_results def clean_results_of_partial_phrases(results) cleaned_results = [] results.each do |current_result| current_result_phrase = current_result[0] cleaned_results << current_result unless results.any? do |other_result| other_result_phrase = other_result[0] is_a_partial_string?(other_result_phrase, current_result_phrase) end end cleaned_results end #is potentially_partial_string a substring of (but not the whole of) containing_string? def is_a_partial_string?(containing_string, potentially_partial_string) return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) ) end def clean_results_of_redirects_to_detected_articles(results) results.delete_if do |phrase, matching_article| results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end results end def clean_results_of_redirects_to_wikified_titles(results, existing_article_titles) results.delete_if do |phrase, matching_article| (matching_article.redirect_target and existing_article_titles.any? {|article_title| matching_article.redirect_target.title.downcase == article_title.downcase}) #Not unicode safe? end results end end #A phrase made up of words class Phrase attr_reader :words def initialize(words) @words = words @phrase = words.join(" ") end def to_s @phrase end def self.build_from_document(document) words = document.split(/[[:space:],.""'']+/) phrase = Phrase.new(words) end end
agrimm/theweatherinlondon
605b06506178c8612be3baccc0b814ff69c020b6
More .gitignore stuff.
diff --git a/log/.gitignore b/log/.gitignore index f780d70..e00f5a5 100644 --- a/log/.gitignore +++ b/log/.gitignore @@ -1,3 +1,5 @@ development.log test.log production.log +mongrel.pid +mongrel.log
agrimm/theweatherinlondon
27c10e1a4957f3ead26a4bb96d31b821c9c8e11f
Changed code repository link to github.
diff --git a/app/views/layouts/read.rhtml b/app/views/layouts/read.rhtml index 153847a..2a2f580 100644 --- a/app/views/layouts/read.rhtml +++ b/app/views/layouts/read.rhtml @@ -1,21 +1,21 @@ <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title>The Weather in London - Article Title Detection</title> <%= stylesheet_link_tag 'scaffold' %> </head> <body> <p style="color: green"><%= flash[:notice] %></p> <%= yield %> <H3>About this site</H3> -<p>This web site written by <a href="mailto:[email protected]">Andrew Grimm</a>, coded in <a href="http://www.rubyonrails.org/">Ruby on Rails</a> and hosted by <a href="http://www.crucial.com.au/">Crucial Paradigm</a>. The source code is available <a href="http://code.google.com/p/theweatherinlondon/">here</a>.</p> +<p>This web site written by <a href="mailto:[email protected]">Andrew Grimm</a>, coded in <a href="http://www.rubyonrails.org/">Ruby on Rails</a> and hosted by <a href="http://www.crucial.com.au/">Crucial Paradigm</a>. The source code is available <a href="http://github.com/agrimm/theweatherinlondon/tree/master">here</a>.</p> </body> </html>
agrimm/theweatherinlondon
e4bcdc686b3a0cd9eb39c40a8f328d5d7badbe2e
Removed stub test from article test, and gitignored database.yml.
diff --git a/config/.gitignore b/config/.gitignore new file mode 100644 index 0000000..b5649dd --- /dev/null +++ b/config/.gitignore @@ -0,0 +1 @@ +database.yml diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 74d31c3..c5afea4 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,238 +1,233 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories fixtures :redirects def setup @empty_document = Document.new("", Repository.find(:first), "auto-detect") @af_uncyclopedia = Repository.find_by_abbreviation("af-uncyclopedia") @auto_detect = "auto-detect" end - # Replace this with your real tests. - def test_truth - assert true - end - #The tests in this method may not make sense right now def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| if rand < 0.04 syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) #Don't remove the inside text parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option else #Remove the inside text parsed_text = pre_syntax_option + post_syntax_option end syntax_test_pairs << [unparsed_text, parsed_text] end end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] assert_equal parsed_text, @empty_document.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" assert_equal ["London"], @empty_document.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" assert_equal "abc mno", @empty_document.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| assert_equal "start finish", @empty_document.parse_non_direct_links(wiki_text) assert_equal "start finish", @empty_document.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text document_text = "[[en:Wikipedia]]" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] results = parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end #Test whether the parser can handle non-ASCII text def test_non_ascii_text repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] phrases.each do |phrase| document_text = phrase results = parse_text_document(document_text, repository, markup) assert_equal 1, results.size, "Problem parsing #{phrase}" end end def test_redirect_target_and_sources misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") assert_equal correct_article, misspelled_article.redirect_target assert_not_equal unrelated_article, misspelled_article.redirect_target assert_nil correct_article.redirect_target assert_equal [misspelled_article], correct_article.redirect_sources assert_not_equal [unrelated_article], correct_article.redirect_sources assert_equal [], misspelled_article.redirect_sources end #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results def test_redirect_cleaning repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") document_text_results_pairs = [] document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] #Just checking the misspelled article exists document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] #Just checking the correctly spelled article exists document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] #If both are unwikified, assert only the correct spelling is wikified document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #If the correct spelling is wikified, don't wikify the incorrect spelling document_text_results_pairs.each do |document_text, expected_results| actual_results = parse_text_document(document_text, repository, markup) assert_equal expected_results, actual_results end end #Given a wikified singular, and an unwikified plural, assert that the plural is not detected as a result #This test is identical to test_redirect_cleaning except it uses lower cases def test_detect_redirected_plurals document_text = "a [[running back]] amongst running backs" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results, "Problem with redirects" end def test_handles_articles_without_redirect_targets maria_theresa_article = Article.find_by_title("Maria Theresa of Austria") document_text = "a [[running back]] amongst running backs was #{maria_theresa_article.title}" expected_results = [ [maria_theresa_article.title, maria_theresa_article] ] actual_results = nil assert_nothing_raised do actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) end assert_equal expected_results, actual_results end def test_handles_underscores_in_wikified_text document_text = "I wish to underscore the fact that a [[running_back]] is a running back no matter what." expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results end def parse_text_document(document_text, repository, markup) document = Article.new_document(document_text, repository, markup) return document.parse end def test_ignore_boring_phrases document_text = "the the the the the the" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results end end
agrimm/theweatherinlondon
05f8b7eab126077d6c4dce0682e897c1a5060892
Created Phrase class.
diff --git a/app/models/article.rb b/app/models/article.rb index 0d1eb68..d8470c8 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,217 +1,233 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end - @words = break_up_phrase(@parsed_document_text) + phrase = Phrase.build_from_document(@parsed_document_text) + @words = phrase.words raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles - #Strategy: split into words, then iterate through the words def parse parse_results = [] 0.upto(@words.size - 1) do |i| i.upto(@words.size - 1) do |j| - phrase = @words[i..j].join(" ") + phrase = Phrase.new(@words[i..j]) unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) break unless @repository.try_this_phrase_or_longer?(phrase) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| - parse_results << [phrase, matching_article] + parse_results << [phrase.to_s, matching_article] end end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) + phrase_string = phrase.to_s #return false #This causes unit tests to fail - #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( - return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? + #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase_string.chars.downcase)} #Unicode safe, too slow? :( + return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase_string.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end - def break_up_phrase(phrase) - words = phrase.split(/[[:space:],.""'']+/) - words - end - #a method to get rid of the duplicate results def clean_results(parse_results, existing_article_titles) cleaned_results = clean_results_of_partial_phrases(parse_results) cleaned_results = clean_results_of_redirects_to_detected_articles(cleaned_results) cleaned_results = clean_results_of_redirects_to_wikified_titles(cleaned_results, existing_article_titles) cleaned_results end #Get rid of results with a phrase shorter than another phrase in parse_results def clean_results_of_partial_phrases(results) cleaned_results = [] results.each do |current_result| current_result_phrase = current_result[0] cleaned_results << current_result unless results.any? do |other_result| other_result_phrase = other_result[0] is_a_partial_string?(other_result_phrase, current_result_phrase) end end cleaned_results end #is potentially_partial_string a substring of (but not the whole of) containing_string? def is_a_partial_string?(containing_string, potentially_partial_string) return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) ) end def clean_results_of_redirects_to_detected_articles(results) results.delete_if do |phrase, matching_article| results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end results end def clean_results_of_redirects_to_wikified_titles(results, existing_article_titles) results.delete_if do |phrase, matching_article| (matching_article.redirect_target and existing_article_titles.any? {|article_title| matching_article.redirect_target.title.downcase == article_title.downcase}) #Not unicode safe? end results end end + +#A phrase made up of words +class Phrase + attr_reader :words + + def initialize(words) + @words = words + @phrase = words.join(" ") + end + + def to_s + @phrase + end + + def self.build_from_document(document) + words = document.split(/[[:space:],.""'']+/) + phrase = Phrase.new(words) + end + +end diff --git a/app/models/repository.rb b/app/models/repository.rb index 451203a..2679518 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,54 +1,48 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") if (abbreviation =~ /(.*)wiki/) return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def find_matching_articles(phrase) return [] if phrase_is_boring?(phrase) - matching_articles = articles.find(:all, :conditions => ["title = ?", phrase], :limit => 1) + matching_articles = articles.find(:all, :conditions => ["title = ?", phrase.to_s], :limit => 1) matching_articles end #Determine if a phrase is boring #Currently, it deems as boring any phrases with no or one boring words def phrase_is_boring?(phrase) - words = break_up_phrase(phrase) + words = phrase.words boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end def try_this_phrase_or_longer?(phrase) if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end - potentially_matching_article = articles.find(:first, :conditions => ["title like ?", phrase + "%"]) + potentially_matching_article = articles.find(:first, :conditions => ["title like ?", phrase.to_s + "%"]) return ! potentially_matching_article.nil? end - #Todo: this method is also in article.rb, indicating a DRY violation - def break_up_phrase(phrase) - words = phrase.split(/[[:space:],.""'']+/) - words - end - #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end end
agrimm/theweatherinlondon
96f54f1857ebbb0d65c8d1345339f590710428aa
Fixed documentation for phrase_is_boring?
diff --git a/app/models/repository.rb b/app/models/repository.rb index c27f87c..451203a 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,56 +1,54 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") if (abbreviation =~ /(.*)wiki/) return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def find_matching_articles(phrase) return [] if phrase_is_boring?(phrase) matching_articles = articles.find(:all, :conditions => ["title = ?", phrase], :limit => 1) matching_articles end #Determine if a phrase is boring - #Currently, it is expected by contract to deem as boring any phrases with no or one boring words - #As a convenience to the calling method, it may deem as boring any phrases that have already been found, but it is not part of the contract, and it won't take into account redirects + #Currently, it deems as boring any phrases with no or one boring words def phrase_is_boring?(phrase) words = break_up_phrase(phrase) - #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end def try_this_phrase_or_longer?(phrase) if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end potentially_matching_article = articles.find(:first, :conditions => ["title like ?", phrase + "%"]) return ! potentially_matching_article.nil? end #Todo: this method is also in article.rb, indicating a DRY violation def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end end
agrimm/theweatherinlondon
2fcf758e9fe373a8fd7e8c80ab463c5e796d43a2
Changed logic of searching to reduce queries.
diff --git a/app/models/article.rb b/app/models/article.rb index d9aba6b..0d1eb68 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,217 +1,217 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end @words = break_up_phrase(@parsed_document_text) raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def parse parse_results = [] 0.upto(@words.size - 1) do |i| i.upto(@words.size - 1) do |j| phrase = @words[i..j].join(" ") unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) + break unless @repository.try_this_phrase_or_longer?(phrase) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end - break unless @repository.try_longer_phrase?(phrase) end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) #return false #This causes unit tests to fail #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #a method to get rid of the duplicate results def clean_results(parse_results, existing_article_titles) cleaned_results = clean_results_of_partial_phrases(parse_results) cleaned_results = clean_results_of_redirects_to_detected_articles(cleaned_results) cleaned_results = clean_results_of_redirects_to_wikified_titles(cleaned_results, existing_article_titles) cleaned_results end #Get rid of results with a phrase shorter than another phrase in parse_results def clean_results_of_partial_phrases(results) cleaned_results = [] results.each do |current_result| current_result_phrase = current_result[0] cleaned_results << current_result unless results.any? do |other_result| other_result_phrase = other_result[0] is_a_partial_string?(other_result_phrase, current_result_phrase) end end cleaned_results end #is potentially_partial_string a substring of (but not the whole of) containing_string? def is_a_partial_string?(containing_string, potentially_partial_string) return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) ) end def clean_results_of_redirects_to_detected_articles(results) results.delete_if do |phrase, matching_article| results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end results end def clean_results_of_redirects_to_wikified_titles(results, existing_article_titles) results.delete_if do |phrase, matching_article| (matching_article.redirect_target and existing_article_titles.any? {|article_title| matching_article.redirect_target.title.downcase == article_title.downcase}) #Not unicode safe? end results end end diff --git a/app/models/repository.rb b/app/models/repository.rb index a04013b..c27f87c 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,57 +1,56 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") if (abbreviation =~ /(.*)wiki/) return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def find_matching_articles(phrase) return [] if phrase_is_boring?(phrase) matching_articles = articles.find(:all, :conditions => ["title = ?", phrase], :limit => 1) matching_articles end #Determine if a phrase is boring #Currently, it is expected by contract to deem as boring any phrases with no or one boring words #As a convenience to the calling method, it may deem as boring any phrases that have already been found, but it is not part of the contract, and it won't take into account redirects def phrase_is_boring?(phrase) words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end - #Informs the caller if they should try a longer phrase than the current one in order to get a match - def try_longer_phrase?(phrase) + def try_this_phrase_or_longer?(phrase) if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end - potentially_matching_articles = articles.find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>1) - return ! potentially_matching_articles.empty? + potentially_matching_article = articles.find(:first, :conditions => ["title like ?", phrase + "%"]) + return ! potentially_matching_article.nil? end #Todo: this method is also in article.rb, indicating a DRY violation def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end end
agrimm/theweatherinlondon
b9d5f6cbfd28e310eda23cbf358255f3826ef277
Refactored clean_results.
diff --git a/app/models/article.rb b/app/models/article.rb index d809cd9..d9aba6b 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,216 +1,217 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end @words = break_up_phrase(@parsed_document_text) raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def parse parse_results = [] 0.upto(@words.size - 1) do |i| i.upto(@words.size - 1) do |j| phrase = @words[i..j].join(" ") unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end break unless @repository.try_longer_phrase?(phrase) end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) #return false #This causes unit tests to fail #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #a method to get rid of the duplicate results - #to do: refactor this code def clean_results(parse_results, existing_article_titles) - #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant - #Get rid of results with a phrase shorter than another phrase in parse_results - #Get rid of results with a phrase already included in cleaned_results - parse_results.uniq! + cleaned_results = clean_results_of_partial_phrases(parse_results) + cleaned_results = clean_results_of_redirects_to_detected_articles(cleaned_results) + cleaned_results = clean_results_of_redirects_to_wikified_titles(cleaned_results, existing_article_titles) + cleaned_results + end + + #Get rid of results with a phrase shorter than another phrase in parse_results + def clean_results_of_partial_phrases(results) cleaned_results = [] - 0.upto(parse_results.size-1) do |i| - is_non_duplicate_result = true - current_result = parse_results[i] - current_result_phrase = parse_results[i][0] - 0.upto(parse_results.size-1) do |j| - next if i == j - other_result_phrase = parse_results[j][0] - #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one - # is_non_duplicate_result = false - # break - #end - if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) - is_non_duplicate_result = false - break - end - end - if is_non_duplicate_result - cleaned_results << current_result + results.each do |current_result| + current_result_phrase = current_result[0] + + cleaned_results << current_result unless results.any? do |other_result| + other_result_phrase = other_result[0] + is_a_partial_string?(other_result_phrase, current_result_phrase) end - end + end + cleaned_results + end + + #is potentially_partial_string a substring of (but not the whole of) containing_string? + def is_a_partial_string?(containing_string, potentially_partial_string) + return (containing_string.size > potentially_partial_string.size and containing_string.include?(potentially_partial_string) ) + end - cleaned_results.delete_if do |phrase, matching_article| - cleaned_results.any? do |other_phrase, other_article| + def clean_results_of_redirects_to_detected_articles(results) + results.delete_if do |phrase, matching_article| + results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end - cleaned_results.delete_if do |phrase, matching_article| - existing_article_titles.any? do |article_title| - (matching_article.redirect_target and matching_article.redirect_target.title.downcase == article_title.downcase) #Not unicode safe? - end + results + end + + def clean_results_of_redirects_to_wikified_titles(results, existing_article_titles) + results.delete_if do |phrase, matching_article| + (matching_article.redirect_target and existing_article_titles.any? {|article_title| matching_article.redirect_target.title.downcase == article_title.downcase}) #Not unicode safe? end - cleaned_results + results end end
agrimm/theweatherinlondon
72966e9f4516495fbfedccbdc7326b1afda41718
Added unit testing for turing underscores in wikified text into spaces.
diff --git a/app/models/article.rb b/app/models/article.rb index 254dee1..d809cd9 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,216 +1,216 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end @words = break_up_phrase(@parsed_document_text) raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def parse parse_results = [] 0.upto(@words.size - 1) do |i| i.upto(@words.size - 1) do |j| phrase = @words[i..j].join(" ") unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) matching_articles = @repository.find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end break unless @repository.try_longer_phrase?(phrase) end end end parse_results = clean_results(parse_results, @existing_article_titles) end #Return true only if the phrase has checked or wikified #Returning false is not a contract violation under any circumstance #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. def phrase_has_definitely_been_checked?(phrase, existing_article_titles) #return false #This causes unit tests to fail #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first - parsed_title = unparsed_title.gsub(/_+/, " ") #This line is not heckle-proof + parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #a method to get rid of the duplicate results #to do: refactor this code def clean_results(parse_results, existing_article_titles) #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results parse_results.uniq! cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one # is_non_duplicate_result = false # break #end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results.delete_if do |phrase, matching_article| cleaned_results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end cleaned_results.delete_if do |phrase, matching_article| existing_article_titles.any? do |article_title| (matching_article.redirect_target and matching_article.redirect_target.title.downcase == article_title.downcase) #Not unicode safe? end end cleaned_results end end diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 055325b..74d31c3 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,231 +1,238 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories fixtures :redirects def setup @empty_document = Document.new("", Repository.find(:first), "auto-detect") @af_uncyclopedia = Repository.find_by_abbreviation("af-uncyclopedia") @auto_detect = "auto-detect" end # Replace this with your real tests. def test_truth assert true end #The tests in this method may not make sense right now def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| if rand < 0.04 syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) #Don't remove the inside text parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option else #Remove the inside text parsed_text = pre_syntax_option + post_syntax_option end syntax_test_pairs << [unparsed_text, parsed_text] end end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] assert_equal parsed_text, @empty_document.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" assert_equal ["London"], @empty_document.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" assert_equal "abc mno", @empty_document.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| assert_equal "start finish", @empty_document.parse_non_direct_links(wiki_text) assert_equal "start finish", @empty_document.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text document_text = "[[en:Wikipedia]]" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] results = parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end #Test whether the parser can handle non-ASCII text def test_non_ascii_text repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] phrases.each do |phrase| document_text = phrase results = parse_text_document(document_text, repository, markup) assert_equal 1, results.size, "Problem parsing #{phrase}" end end def test_redirect_target_and_sources misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") assert_equal correct_article, misspelled_article.redirect_target assert_not_equal unrelated_article, misspelled_article.redirect_target assert_nil correct_article.redirect_target assert_equal [misspelled_article], correct_article.redirect_sources assert_not_equal [unrelated_article], correct_article.redirect_sources assert_equal [], misspelled_article.redirect_sources end #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results def test_redirect_cleaning repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") document_text_results_pairs = [] document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] #Just checking the misspelled article exists document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] #Just checking the correctly spelled article exists document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] #If both are unwikified, assert only the correct spelling is wikified document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #If the correct spelling is wikified, don't wikify the incorrect spelling document_text_results_pairs.each do |document_text, expected_results| actual_results = parse_text_document(document_text, repository, markup) assert_equal expected_results, actual_results end end #Given a wikified singular, and an unwikified plural, assert that the plural is not detected as a result #This test is identical to test_redirect_cleaning except it uses lower cases def test_detect_redirected_plurals document_text = "a [[running back]] amongst running backs" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results, "Problem with redirects" end def test_handles_articles_without_redirect_targets maria_theresa_article = Article.find_by_title("Maria Theresa of Austria") document_text = "a [[running back]] amongst running backs was #{maria_theresa_article.title}" expected_results = [ [maria_theresa_article.title, maria_theresa_article] ] actual_results = nil assert_nothing_raised do actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) end assert_equal expected_results, actual_results end + def test_handles_underscores_in_wikified_text + document_text = "I wish to underscore the fact that a [[running_back]] is a running back no matter what." + expected_results = [] + actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) + assert_equal expected_results, actual_results + end + def parse_text_document(document_text, repository, markup) document = Article.new_document(document_text, repository, markup) return document.parse end def test_ignore_boring_phrases document_text = "the the the the the the" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results end end
agrimm/theweatherinlondon
20dff9437a9827949ab08359c795c8ed17fbc0fc
Turned off breakpoint server.
diff --git a/config/environments/development.rb b/config/environments/development.rb index 0589aa9..b4ecc7a 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -1,21 +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 +#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
agrimm/theweatherinlondon
60ca32263243f5e9270e9573e33b128df1cb0e80
Added log files to ignore to .gitignore .
diff --git a/log/.gitignore b/log/.gitignore index e69de29..f780d70 100644 --- a/log/.gitignore +++ b/log/.gitignore @@ -0,0 +1,3 @@ +development.log +test.log +production.log
agrimm/theweatherinlondon
e4d022edf600f35663ee5c1b3da91be8d8215a4b
Restored empty directories lost in git svn import.
diff --git a/components/.gitignore b/components/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/lib/tasks/.gitignore b/lib/tasks/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/log/.gitignore b/log/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/test/mocks/development/.gitignore b/test/mocks/development/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/test/mocks/test/.gitignore b/test/mocks/test/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/plugins/.gitignore b/vendor/plugins/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/actionpack/test/fixtures/public/javascripts/cache/.gitignore b/vendor/rails/actionpack/test/fixtures/public/javascripts/cache/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/lib/rails_generator/generators/components/web_service/templates/.gitignore b/vendor/rails/railties/lib/rails_generator/generators/components/web_service/templates/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/test/fixtures/lib/missing_class/templates/.gitignore b/vendor/rails/railties/test/fixtures/lib/missing_class/templates/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/test/fixtures/lib/missing_generator/templates/.gitignore b/vendor/rails/railties/test/fixtures/lib/missing_generator/templates/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/test/fixtures/lib/missing_templates/.gitignore b/vendor/rails/railties/test/fixtures/lib/missing_templates/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/test/fixtures/plugins/alternate/a/lib/.gitignore b/vendor/rails/railties/test/fixtures/plugins/alternate/a/lib/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/.gitignore b/vendor/rails/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/rails/railties/test/fixtures/plugins/default/empty/.gitignore b/vendor/rails/railties/test/fixtures/plugins/default/empty/.gitignore new file mode 100644 index 0000000..e69de29
agrimm/theweatherinlondon
1544288a1f82111e5d2c5ac56515ef9d3c168f6e
Moved examining if a phrase has been encountered before from repository to article model.
diff --git a/app/models/article.rb b/app/models/article.rb index 88cf995..254dee1 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,205 +1,216 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end @words = break_up_phrase(@parsed_document_text) raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def parse parse_results = [] 0.upto(@words.size - 1) do |i| i.upto(@words.size - 1) do |j| phrase = @words[i..j].join(" ") - matching_articles = @repository.find_matching_articles(phrase, @existing_article_titles) - matching_articles.each do |matching_article| - parse_results << [phrase, matching_article] + unless phrase_has_definitely_been_checked?(phrase, @existing_article_titles) + matching_articles = @repository.find_matching_articles(phrase) + matching_articles.each do |matching_article| + parse_results << [phrase, matching_article] + end + break unless @repository.try_longer_phrase?(phrase) end - break unless @repository.try_longer_phrase?(phrase, @existing_article_titles) end end parse_results = clean_results(parse_results, @existing_article_titles) end + #Return true only if the phrase has checked or wikified + #Returning false is not a contract violation under any circumstance + #To do: returning false can cause a unit test to fail. This indicates that other parts of the program are relying on uncontracted behaviour. + def phrase_has_definitely_been_checked?(phrase, existing_article_titles) + #return false #This causes unit tests to fail + #return existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( + return existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? + end + #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") #This line is not heckle-proof parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #a method to get rid of the duplicate results #to do: refactor this code def clean_results(parse_results, existing_article_titles) #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results parse_results.uniq! cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one # is_non_duplicate_result = false # break #end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results.delete_if do |phrase, matching_article| cleaned_results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end cleaned_results.delete_if do |phrase, matching_article| existing_article_titles.any? do |article_title| (matching_article.redirect_target and matching_article.redirect_target.title.downcase == article_title.downcase) #Not unicode safe? end end cleaned_results end end diff --git a/app/models/repository.rb b/app/models/repository.rb index 289aa03..a04013b 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,61 +1,57 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") if (abbreviation =~ /(.*)wiki/) return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case - def find_matching_articles(phrase, existing_article_titles) - return [] if phrase_is_boring?(phrase, existing_article_titles) + def find_matching_articles(phrase) + return [] if phrase_is_boring?(phrase) matching_articles = articles.find(:all, :conditions => ["title = ?", phrase], :limit => 1) matching_articles end #Determine if a phrase is boring #Currently, it is expected by contract to deem as boring any phrases with no or one boring words #As a convenience to the calling method, it may deem as boring any phrases that have already been found, but it is not part of the contract, and it won't take into account redirects - def phrase_is_boring?(phrase, existing_article_titles) - #if existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( - if existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? - return true - end + def phrase_is_boring?(phrase) words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end #Informs the caller if they should try a longer phrase than the current one in order to get a match - def try_longer_phrase?(phrase, existing_article_titles) - if phrase_is_boring?(phrase, existing_article_titles) + def try_longer_phrase?(phrase) + if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end potentially_matching_articles = articles.find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>1) return ! potentially_matching_articles.empty? end #Todo: this method is also in article.rb, indicating a DRY violation def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end end
agrimm/theweatherinlondon
832c0e2a0c290e75b4e28ebc4674a4834ab0f7f8
Added unit testing to ensure that boring phrases are not included in the result.
diff --git a/test/fixtures/articles.yml b/test/fixtures/articles.yml index ee676f4..4b5e333 100644 --- a/test/fixtures/articles.yml +++ b/test/fixtures/articles.yml @@ -1,80 +1,88 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html Maria Theresa of Austria: id: 1 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_of_Austria title: Maria Theresa of Austria repository_id: 1 local_id: 1 Maria Theresa: id: 2 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa title: Maria Theresa repository_id: 1 local_id: 2 #ASCII, multiple capital letters UAE in English: id: 3 uri: http://en.wikipedia.org/wiki/United_Arab_Emirates title: United Arab Emirates repository_id: 1 local_id: 3 #ASCII, only one capital letter Prime minister: id: 4 uri: http://en.wikipedia.org/wiki/Prime_minister title: Prime minister repository_id: 1 local_id: 4 #Accented letter Internet cafe: id: 5 uri: http://en.wikipedia.org/wiki/Internet_caf%C3%A9 title: Internet caf<%= "\xc3\xa9"%> repository_id: 1 local_id: 5 #Arabic for internet cafe (I think) Arabic internet cafe: id: 6 uri: http://ar.wikipedia.org/wiki/%D9%85%D9%82%D9%87%D9%89_%D8%A5%D9%86%D8%AA%D8%B1%D9%86%D8%AA title: <%= "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA"%> repository_id: 1 local_id: 6 #Reversed string for internet cafe (I think) Reversed arabic internet cafe: id: 7 uri: http://www.example.com/arabic_internet_cafe_reversed title: <%= "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"%> repository_id: 1 local_id: 7 #Obviously a typo Maria Thesa ov Austria: id: 8 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_ov_Austria title: Maria Theresa ov Austria repository_id: 1 local_id: 8 #Singular Running back: id: 9 uri: http://en.wikipedia.org/wiki/Running_back title: Running back repository_id: 1 local_id: 9 #Plural Running backs: id: 10 uri: http://en.wikipedia.org/wiki/Running_backs title: Running backs repository_id: 1 local_id: 10 +#A boring title +The the: + id: 11 + uri: http://af.uncyclopedia.wikia.com/wiki/The_the + title: The the + repository_id: 1 + local_id: 11 + diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index c82c312..055325b 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,224 +1,231 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories fixtures :redirects def setup @empty_document = Document.new("", Repository.find(:first), "auto-detect") @af_uncyclopedia = Repository.find_by_abbreviation("af-uncyclopedia") @auto_detect = "auto-detect" end # Replace this with your real tests. def test_truth assert true end #The tests in this method may not make sense right now def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| if rand < 0.04 syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) #Don't remove the inside text parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option else #Remove the inside text parsed_text = pre_syntax_option + post_syntax_option end syntax_test_pairs << [unparsed_text, parsed_text] end end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] assert_equal parsed_text, @empty_document.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" assert_equal ["London"], @empty_document.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" assert_equal "abc mno", @empty_document.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| assert_equal "start finish", @empty_document.parse_non_direct_links(wiki_text) assert_equal "start finish", @empty_document.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text document_text = "[[en:Wikipedia]]" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] results = parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end #Test whether the parser can handle non-ASCII text def test_non_ascii_text repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] phrases.each do |phrase| document_text = phrase results = parse_text_document(document_text, repository, markup) assert_equal 1, results.size, "Problem parsing #{phrase}" end end def test_redirect_target_and_sources misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") assert_equal correct_article, misspelled_article.redirect_target assert_not_equal unrelated_article, misspelled_article.redirect_target assert_nil correct_article.redirect_target assert_equal [misspelled_article], correct_article.redirect_sources assert_not_equal [unrelated_article], correct_article.redirect_sources assert_equal [], misspelled_article.redirect_sources end #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results def test_redirect_cleaning repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") document_text_results_pairs = [] document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] #Just checking the misspelled article exists document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] #Just checking the correctly spelled article exists document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] #If both are unwikified, assert only the correct spelling is wikified document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #If the correct spelling is wikified, don't wikify the incorrect spelling document_text_results_pairs.each do |document_text, expected_results| actual_results = parse_text_document(document_text, repository, markup) assert_equal expected_results, actual_results end end #Given a wikified singular, and an unwikified plural, assert that the plural is not detected as a result #This test is identical to test_redirect_cleaning except it uses lower cases def test_detect_redirected_plurals document_text = "a [[running back]] amongst running backs" expected_results = [] actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) assert_equal expected_results, actual_results, "Problem with redirects" end def test_handles_articles_without_redirect_targets maria_theresa_article = Article.find_by_title("Maria Theresa of Austria") document_text = "a [[running back]] amongst running backs was #{maria_theresa_article.title}" expected_results = [ [maria_theresa_article.title, maria_theresa_article] ] actual_results = nil assert_nothing_raised do actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) end assert_equal expected_results, actual_results end def parse_text_document(document_text, repository, markup) document = Article.new_document(document_text, repository, markup) return document.parse end + def test_ignore_boring_phrases + document_text = "the the the the the the" + expected_results = [] + actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) + assert_equal expected_results, actual_results + end + end
agrimm/theweatherinlondon
e31acdb8d2691851cf4211adb80aa9dae8c968df
Set default and persistance for choice of repository.
diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index 7460a67..790c4c9 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,36 +1,45 @@ class ReadController < ApplicationController def read @repository_choices = Repository.find(:all).map {|rc| [rc.short_description, rc.id]} + @default_repository_choice = params[:repository_id].to_i + if params[:repository_id].nil? + hard_wired_preference = "English language Wikipedia" + @repository_choices.each do |short_description, id_number| + if short_description == hard_wired_preference + @default_repository_choice = id_number + end + end + end @markup_choices = [ ["Auto-detect (default)", "auto-detect"], ["MediaWiki formatting", "mediawiki"], ["Plain text", "plain"] ] if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end repository = Repository.find(params[:repository_id]) unless repository @errors << "Can't find repository" end markup = params[:markup] unless @markup_choices.map{|pair| pair.last}.include?(markup) @errors << "Invalid markup choice" end if @errors.empty? begin document = Article.new_document(document_text, repository, markup) @parse_results = document.parse rescue ArgumentError => error if error.message == "Document has too many words" @errors << "Please submit a text fewer than #{Repository.maximum_allowed_document_size} words long" else raise end end end end end end diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index 869fccc..1fb6bf9 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,51 +1,51 @@ <% unless @errors.blank? %> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> <p>(Maximum <%= Repository.maximum_allowed_document_size %> words)</p> <% form_tag(:action => :read) do %> <table> <tr><td colspan=2> <%= text_area_tag(:document_text, h(params[:document_text]), :cols=> 80, :rows=> 10) %></td></tr> <tr><td>Web site:</td> -<td><%= select_tag "repository_id", options_for_select(@repository_choices) %></td></tr> +<td><%= select_tag(:repository_id, options_for_select(@repository_choices, @default_repository_choice) )%></td></tr> <tr><td>Markup (if any)</td> <td><%= select_tag "markup", options_for_select(@markup_choices) %></td></tr> <tr><td> <%= submit_tag("Submit text") %> </td><td></td></tr> </table> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %> <H2>How to use The Weather in London</H2> <p>The Weather in London provides a different kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> <p>For example, if you submitted <a href="http://en.wikinews.org/wiki/Last_Titan_launch_complex_at_Cape_Canaveral_demolished">this block of text</a></p> <blockquote>Launch Complex 40 (LC-40) at the Cape Canaveral Air Force Station, Merritt Island, Florida has been demolished. The Mobile Service Structure (MSS), which was once used to load payloads onto Titan III and Titan IV rockets, was toppled by explosive charges at 13:00 GMT.</blockquote> <p>you would discover that Wikipedia has articles on Launch Complex, Cape Canaveral Air Force Station, Merritt Island, Titan III and Titan IV.</p> <p>You can also choose to see if a block of text contains a person or electorate in the <a href="http://en.wikipedia.org/wiki/Australian_House_of_Representatives">Australian House of Representatives</a>. This is possibly of marginal utility, but is an example of this concept not just applying for wikis.</p> <p>Currently, only phrases with more than one non-trivial word are checked, rather than single words, to reduce clutter.</p>
agrimm/theweatherinlondon
4bec90f35515c6da6d8810ec84b14f002d6f7416
Added checking that results found don't redirect to already wikified article titles.
diff --git a/app/models/article.rb b/app/models/article.rb index 9a68ab5..88cf995 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,200 +1,205 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end #To do: fix this kludge? def self.new_document(document_text, repository, markup) return Document.new(document_text, repository, markup) end end #A document submitted by the user class Document def initialize(document_text, repository, markup) @repository = repository if (markup == "auto-detect") #Turn into symbol markup = markup_autodetect(document_text) end if (markup == "mediawiki") @parsed_document_text = parse_wiki_text(document_text.dup) @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) else @parsed_document_text = document_text.dup @existing_article_titles = [] end @words = break_up_phrase(@parsed_document_text) raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def parse parse_results = [] 0.upto(@words.size - 1) do |i| i.upto(@words.size - 1) do |j| phrase = @words[i..j].join(" ") matching_articles = @repository.find_matching_articles(phrase, @existing_article_titles) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end break unless @repository.try_longer_phrase?(phrase, @existing_article_titles) end end - parse_results = clean_results(parse_results) + parse_results = clean_results(parse_results, @existing_article_titles) end #Determine if the text is in some sort of markup def markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def parse_wiki_text(wiki_text) wiki_text = parse_nowiki(wiki_text) wiki_text = parse_templates(wiki_text) wiki_text = parse_paired_tags(wiki_text) wiki_text = parse_unpaired_tags(wiki_text) wiki_text = parse_non_direct_links(wiki_text) wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first - parsed_title = unparsed_title.gsub(/_+/, " ") + parsed_title = unparsed_title.gsub(/_+/, " ") #This line is not heckle-proof parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #a method to get rid of the duplicate results - #to do: remove any results here that are redirects to existing wikified results - def clean_results(parse_results) + #to do: refactor this code + def clean_results(parse_results, existing_article_titles) #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results parse_results.uniq! cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one # is_non_duplicate_result = false # break #end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results.delete_if do |phrase, matching_article| cleaned_results.any? do |other_phrase, other_article| matching_article.redirect_target == other_article end end + cleaned_results.delete_if do |phrase, matching_article| + existing_article_titles.any? do |article_title| + (matching_article.redirect_target and matching_article.redirect_target.title.downcase == article_title.downcase) #Not unicode safe? + end + end cleaned_results end end diff --git a/app/models/repository.rb b/app/models/repository.rb index 1645eed..289aa03 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,61 +1,61 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") if (abbreviation =~ /(.*)wiki/) return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def find_matching_articles(phrase, existing_article_titles) return [] if phrase_is_boring?(phrase, existing_article_titles) matching_articles = articles.find(:all, :conditions => ["title = ?", phrase], :limit => 1) matching_articles end #Determine if a phrase is boring - #That is, it has one or zero non-boring words - # and that the wiki text doesn't already link to it (if applicable) + #Currently, it is expected by contract to deem as boring any phrases with no or one boring words + #As a convenience to the calling method, it may deem as boring any phrases that have already been found, but it is not part of the contract, and it won't take into account redirects def phrase_is_boring?(phrase, existing_article_titles) #if existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( if existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? return true end words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end #Informs the caller if they should try a longer phrase than the current one in order to get a match def try_longer_phrase?(phrase, existing_article_titles) if phrase_is_boring?(phrase, existing_article_titles) return true #Otherwise it chews up too much server time end potentially_matching_articles = articles.find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>1) return ! potentially_matching_articles.empty? end #Todo: this method is also in article.rb, indicating a DRY violation def break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end end diff --git a/test/fixtures/articles.yml b/test/fixtures/articles.yml index 3c90df1..ee676f4 100644 --- a/test/fixtures/articles.yml +++ b/test/fixtures/articles.yml @@ -1,63 +1,80 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html Maria Theresa of Austria: id: 1 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_of_Austria title: Maria Theresa of Austria repository_id: 1 local_id: 1 Maria Theresa: id: 2 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa title: Maria Theresa repository_id: 1 local_id: 2 #ASCII, multiple capital letters UAE in English: id: 3 uri: http://en.wikipedia.org/wiki/United_Arab_Emirates title: United Arab Emirates repository_id: 1 local_id: 3 #ASCII, only one capital letter Prime minister: id: 4 uri: http://en.wikipedia.org/wiki/Prime_minister title: Prime minister repository_id: 1 local_id: 4 #Accented letter Internet cafe: id: 5 uri: http://en.wikipedia.org/wiki/Internet_caf%C3%A9 title: Internet caf<%= "\xc3\xa9"%> repository_id: 1 local_id: 5 #Arabic for internet cafe (I think) Arabic internet cafe: id: 6 uri: http://ar.wikipedia.org/wiki/%D9%85%D9%82%D9%87%D9%89_%D8%A5%D9%86%D8%AA%D8%B1%D9%86%D8%AA title: <%= "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA"%> repository_id: 1 local_id: 6 #Reversed string for internet cafe (I think) Reversed arabic internet cafe: id: 7 uri: http://www.example.com/arabic_internet_cafe_reversed title: <%= "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"%> repository_id: 1 local_id: 7 #Obviously a typo Maria Thesa ov Austria: id: 8 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_ov_Austria title: Maria Theresa ov Austria repository_id: 1 local_id: 8 + +#Singular +Running back: + id: 9 + uri: http://en.wikipedia.org/wiki/Running_back + title: Running back + repository_id: 1 + local_id: 9 + +#Plural +Running backs: + id: 10 + uri: http://en.wikipedia.org/wiki/Running_backs + title: Running backs + repository_id: 1 + local_id: 10 + diff --git a/test/fixtures/redirects.yml b/test/fixtures/redirects.yml index 7f05b2c..0e40fd5 100644 --- a/test/fixtures/redirects.yml +++ b/test/fixtures/redirects.yml @@ -1,7 +1,12 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html redirect_1: redirect_source_repository_id: 1 redirect_source_local_id: 8 redirect_target_title: Maria Theresa of Austria +running_backs_redirect: + redirect_source_repository_id: 1 + redirect_source_local_id: 10 + redirect_target_title: Running back + diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 2ae9f12..c82c312 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,202 +1,224 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories fixtures :redirects def setup @empty_document = Document.new("", Repository.find(:first), "auto-detect") + @af_uncyclopedia = Repository.find_by_abbreviation("af-uncyclopedia") + @auto_detect = "auto-detect" end # Replace this with your real tests. def test_truth assert true end #The tests in this method may not make sense right now def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| if rand < 0.04 syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) #Don't remove the inside text parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option else #Remove the inside text parsed_text = pre_syntax_option + post_syntax_option end syntax_test_pairs << [unparsed_text, parsed_text] end end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] assert_equal parsed_text, @empty_document.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" assert_equal ["London"], @empty_document.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" assert_equal "abc mno", @empty_document.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| assert_equal "start finish", @empty_document.parse_non_direct_links(wiki_text) assert_equal "start finish", @empty_document.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text document_text = "[[en:Wikipedia]]" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] results = parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end #Test whether the parser can handle non-ASCII text def test_non_ascii_text repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] phrases.each do |phrase| document_text = phrase results = parse_text_document(document_text, repository, markup) assert_equal 1, results.size, "Problem parsing #{phrase}" end end def test_redirect_target_and_sources misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") assert_equal correct_article, misspelled_article.redirect_target assert_not_equal unrelated_article, misspelled_article.redirect_target assert_nil correct_article.redirect_target assert_equal [misspelled_article], correct_article.redirect_sources assert_not_equal [unrelated_article], correct_article.redirect_sources assert_equal [], misspelled_article.redirect_sources end #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results def test_redirect_cleaning repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") document_text_results_pairs = [] - document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] - document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] - document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] - #document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #This one should fail right now + document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] #Just checking the misspelled article exists + document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] #Just checking the correctly spelled article exists + document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] #If both are unwikified, assert only the correct spelling is wikified + document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #If the correct spelling is wikified, don't wikify the incorrect spelling document_text_results_pairs.each do |document_text, expected_results| actual_results = parse_text_document(document_text, repository, markup) assert_equal expected_results, actual_results end end + #Given a wikified singular, and an unwikified plural, assert that the plural is not detected as a result + #This test is identical to test_redirect_cleaning except it uses lower cases + def test_detect_redirected_plurals + document_text = "a [[running back]] amongst running backs" + expected_results = [] + actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) + assert_equal expected_results, actual_results, "Problem with redirects" + end + + def test_handles_articles_without_redirect_targets + maria_theresa_article = Article.find_by_title("Maria Theresa of Austria") + document_text = "a [[running back]] amongst running backs was #{maria_theresa_article.title}" + expected_results = [ [maria_theresa_article.title, maria_theresa_article] ] + actual_results = nil + assert_nothing_raised do + actual_results = parse_text_document(document_text, @af_uncyclopedia, @auto_detect) + end + assert_equal expected_results, actual_results + end + def parse_text_document(document_text, repository, markup) document = Article.new_document(document_text, repository, markup) return document.parse end end
agrimm/theweatherinlondon
96e813c31e46a01c0c0c26e38d2cc611381f9977
Created a new class Document, and moved several methods from Article to Document or Repository.
diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index f972015..7460a67 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,35 +1,36 @@ class ReadController < ApplicationController def read @repository_choices = Repository.find(:all).map {|rc| [rc.short_description, rc.id]} @markup_choices = [ ["Auto-detect (default)", "auto-detect"], ["MediaWiki formatting", "mediawiki"], ["Plain text", "plain"] ] if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end repository = Repository.find(params[:repository_id]) unless repository @errors << "Can't find repository" end markup = params[:markup] unless @markup_choices.map{|pair| pair.last}.include?(markup) @errors << "Invalid markup choice" end if @errors.empty? begin - @parse_results = Article.parse_text_document(document_text, repository, markup) + document = Article.new_document(document_text, repository, markup) + @parse_results = document.parse rescue ArgumentError => error if error.message == "Document has too many words" - @errors << "Please submit a text fewer than #{Article.maximum_allowed_document_size} words long" + @errors << "Please submit a text fewer than #{Repository.maximum_allowed_document_size} words long" else raise end end end end end end diff --git a/app/models/article.rb b/app/models/article.rb index 16dd23a..9a68ab5 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,240 +1,200 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository - #Return the maximum length a document should be, to avoid server resource issues - def self.maximum_allowed_document_size - 15000 - end - #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end #If the article is a redirect, return the redirect target, else return nil def redirect_target if defined?(@redirect_target) @redirect_target else results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 @redirect_target = results.first end end def redirect_sources if defined?(@redirect_sources) @redirect_sources else #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) end end - - def self.break_up_phrase(phrase) - words = phrase.split(/[[:space:],.""'']+/) - words + #To do: fix this kludge? + def self.new_document(document_text, repository, markup) + return Document.new(document_text, repository, markup) end - #Determine if a phrase is boring - #That is, it has one or zero non-boring words - # and that the wiki text doesn't already link to it (if applicable) - def self.phrase_is_boring?(phrase, existing_article_titles) - #if existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( - if existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? - return true - end - words = break_up_phrase(phrase) - #count how many words are non-boring - boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} - number_non_boring_words = 0 - words.each do |word| - number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? - #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe - end - return true unless number_non_boring_words > 1 - end +end - #Return all articles that match the requested phrase - #Probably should only return one article, but return an array just in case - def self.find_matching_articles(phrase, repository, existing_article_titles) - return [] if phrase_is_boring?(phrase, existing_article_titles) - articles = find(:all, :conditions => ["title = ? and repository_id = ?", phrase, repository], :limit => 1) - articles - end +#A document submitted by the user +class Document - #Informs the caller if they should try a longer phrase than the current one in order to get a match - def self.try_longer_phrase?(phrase, repository, existing_article_titles) - if phrase_is_boring?(phrase, existing_article_titles) - return true #Otherwise it chews up too much server time + def initialize(document_text, repository, markup) + @repository = repository + if (markup == "auto-detect") #Turn into symbol + markup = markup_autodetect(document_text) + end + if (markup == "mediawiki") + @parsed_document_text = parse_wiki_text(document_text.dup) + @existing_article_titles = parse_existing_wiki_links(@parsed_document_text) + else + @parsed_document_text = document_text.dup + @existing_article_titles = [] end - potentially_matching_articles = find(:all, :conditions => ["title like ? and repository_id = ?", phrase + "%", repository], :limit=>1) - return !potentially_matching_articles.empty? + @words = break_up_phrase(@parsed_document_text) + raise(ArgumentError, "Document has too many words") if @words.size > Repository.maximum_allowed_document_size end - #The main method called from the controller #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words - def self.parse_text_document(document_text, repository, markup) + def parse parse_results = [] - words = break_up_phrase(document_text) - raise(ArgumentError, "Document has too many words") if words.size > maximum_allowed_document_size - if (markup == "auto-detect") - markup = self.markup_autodetect(document_text) - end - if (markup == "mediawiki") - wiki_text = document_text.dup - parsed_wiki_text = self.parse_wiki_text(wiki_text) - existing_article_titles = self.parse_existing_wiki_links(parsed_wiki_text) - else - existing_article_titles = [] - end - i = 0 - while(true) - j = 0 - phrase = words[i + j] - while(true) - matching_articles = find_matching_articles(phrase, repository, existing_article_titles) + 0.upto(@words.size - 1) do |i| + i.upto(@words.size - 1) do |j| + phrase = @words[i..j].join(" ") + matching_articles = @repository.find_matching_articles(phrase, @existing_article_titles) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end - - break unless (try_longer_phrase?(phrase, repository, existing_article_titles) and i + j + 1 < words.size) - j = j + 1 - phrase += " " - phrase += words[i + j] + break unless @repository.try_longer_phrase?(phrase, @existing_article_titles) end - - break unless (i + 1 < words.size) - i = i + 1 end - - cleaned_results = clean_results(parse_results) - cleaned_results + parse_results = clean_results(parse_results) end - #a method to get rid of the duplicate results - #to do: remove any results here that are redirects to existing wikified results - def self.clean_results(parse_results) - #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant - #Get rid of results with a phrase shorter than another phrase in parse_results - #Get rid of results with a phrase already included in cleaned_results - parse_results.uniq! - cleaned_results = [] - 0.upto(parse_results.size-1) do |i| - is_non_duplicate_result = true - current_result = parse_results[i] - current_result_phrase = parse_results[i][0] - 0.upto(parse_results.size-1) do |j| - next if i == j - other_result_phrase = parse_results[j][0] - #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one - # is_non_duplicate_result = false - # break - #end - if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) - is_non_duplicate_result = false - break - end - end - if is_non_duplicate_result - cleaned_results << current_result - end - end - - cleaned_results.delete_if do |phrase, matching_article| - cleaned_results.any? do |other_phrase, other_article| - matching_article.redirect_target == other_article - end + #Determine if the text is in some sort of markup + def markup_autodetect(document_text) + markup = "plain" + if document_text =~ %r{\[\[[^\[\]]+\]\]}im + markup = "mediawiki" end - cleaned_results + markup end #Remove from MediaWiki text anything that is surrounded by <nowiki> - def self.parse_nowiki(wiki_text) + def parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template - def self.parse_templates(wiki_text) + def parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now - def self.parse_external_links(wiki_text) + def parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax - def self.parse_paired_tags(wiki_text) + def parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax - def self.parse_unpaired_tags(wiki_text) + def parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) - def self.parse_non_direct_links(wiki_text) + def parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program - def self.parse_wiki_text(wiki_text) - wiki_text = self.parse_nowiki(wiki_text) - wiki_text = self.parse_templates(wiki_text) - wiki_text = self.parse_paired_tags(wiki_text) - wiki_text = self.parse_unpaired_tags(wiki_text) - wiki_text = self.parse_non_direct_links(wiki_text) - wiki_text = self.parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now + def parse_wiki_text(wiki_text) + wiki_text = parse_nowiki(wiki_text) + wiki_text = parse_templates(wiki_text) + wiki_text = parse_paired_tags(wiki_text) + wiki_text = parse_unpaired_tags(wiki_text) + wiki_text = parse_non_direct_links(wiki_text) + wiki_text = parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text - def self.parse_existing_wiki_links(wiki_text) + def parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end - #Determine if the text is in some sort of markup - def self.markup_autodetect(document_text) - markup = "plain" - if document_text =~ %r{\[\[[^\[\]]+\]\]}im - markup = "mediawiki" + def break_up_phrase(phrase) + words = phrase.split(/[[:space:],.""'']+/) + words + end + + #a method to get rid of the duplicate results + #to do: remove any results here that are redirects to existing wikified results + def clean_results(parse_results) + #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant + #Get rid of results with a phrase shorter than another phrase in parse_results + #Get rid of results with a phrase already included in cleaned_results + parse_results.uniq! + cleaned_results = [] + 0.upto(parse_results.size-1) do |i| + is_non_duplicate_result = true + current_result = parse_results[i] + current_result_phrase = parse_results[i][0] + 0.upto(parse_results.size-1) do |j| + next if i == j + other_result_phrase = parse_results[j][0] + #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one + # is_non_duplicate_result = false + # break + #end + if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) + is_non_duplicate_result = false + break + end + end + if is_non_duplicate_result + cleaned_results << current_result + end + end + + cleaned_results.delete_if do |phrase, matching_article| + cleaned_results.any? do |other_phrase, other_article| + matching_article.redirect_target == other_article + end end - markup + cleaned_results end end diff --git a/app/models/repository.rb b/app/models/repository.rb index dcfcfb1..1645eed 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,14 +1,61 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") if (abbreviation =~ /(.*)wiki/) return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end + #Return all articles that match the requested phrase + #Probably should only return one article, but return an array just in case + def find_matching_articles(phrase, existing_article_titles) + return [] if phrase_is_boring?(phrase, existing_article_titles) + matching_articles = articles.find(:all, :conditions => ["title = ?", phrase], :limit => 1) + matching_articles + end + + #Determine if a phrase is boring + #That is, it has one or zero non-boring words + # and that the wiki text doesn't already link to it (if applicable) + def phrase_is_boring?(phrase, existing_article_titles) + #if existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( + if existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? + return true + end + words = break_up_phrase(phrase) + #count how many words are non-boring + boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} + number_non_boring_words = 0 + words.each do |word| + number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? + #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe + end + return true unless number_non_boring_words > 1 + end + + #Informs the caller if they should try a longer phrase than the current one in order to get a match + def try_longer_phrase?(phrase, existing_article_titles) + if phrase_is_boring?(phrase, existing_article_titles) + return true #Otherwise it chews up too much server time + end + potentially_matching_articles = articles.find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>1) + return ! potentially_matching_articles.empty? + end + + #Todo: this method is also in article.rb, indicating a DRY violation + def break_up_phrase(phrase) + words = phrase.split(/[[:space:],.""'']+/) + words + end + + #Return the maximum length a document should be, to avoid server resource issues + def self.maximum_allowed_document_size + 15000 + end + end diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index f09f91f..869fccc 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,51 +1,51 @@ <% unless @errors.blank? %> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> -<p>(Maximum <%= Article.maximum_allowed_document_size %> words)</p> +<p>(Maximum <%= Repository.maximum_allowed_document_size %> words)</p> <% form_tag(:action => :read) do %> <table> <tr><td colspan=2> <%= text_area_tag(:document_text, h(params[:document_text]), :cols=> 80, :rows=> 10) %></td></tr> <tr><td>Web site:</td> <td><%= select_tag "repository_id", options_for_select(@repository_choices) %></td></tr> <tr><td>Markup (if any)</td> <td><%= select_tag "markup", options_for_select(@markup_choices) %></td></tr> <tr><td> <%= submit_tag("Submit text") %> </td><td></td></tr> </table> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %> <H2>How to use The Weather in London</H2> <p>The Weather in London provides a different kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> <p>For example, if you submitted <a href="http://en.wikinews.org/wiki/Last_Titan_launch_complex_at_Cape_Canaveral_demolished">this block of text</a></p> <blockquote>Launch Complex 40 (LC-40) at the Cape Canaveral Air Force Station, Merritt Island, Florida has been demolished. The Mobile Service Structure (MSS), which was once used to load payloads onto Titan III and Titan IV rockets, was toppled by explosive charges at 13:00 GMT.</blockquote> <p>you would discover that Wikipedia has articles on Launch Complex, Cape Canaveral Air Force Station, Merritt Island, Titan III and Titan IV.</p> <p>You can also choose to see if a block of text contains a person or electorate in the <a href="http://en.wikipedia.org/wiki/Australian_House_of_Representatives">Australian House of Representatives</a>. This is possibly of marginal utility, but is an example of this concept not just applying for wikis.</p> <p>Currently, only phrases with more than one non-trivial word are checked, rather than single words, to reduce clutter.</p> diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 2364efd..2ae9f12 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,193 +1,202 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories fixtures :redirects + def setup + @empty_document = Document.new("", Repository.find(:first), "auto-detect") + end + # Replace this with your real tests. def test_truth assert true end #The tests in this method may not make sense right now def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| if rand < 0.04 syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) #Don't remove the inside text parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option else #Remove the inside text parsed_text = pre_syntax_option + post_syntax_option end syntax_test_pairs << [unparsed_text, parsed_text] end end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] - assert_equal parsed_text, Article.send(method_symbol, unparsed_text) + assert_equal parsed_text, @empty_document.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" - assert_equal ["London"], Article.parse_existing_wiki_links(wiki_text) + assert_equal ["London"], @empty_document.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" - assert_equal "abc mno", Article.parse_templates(wiki_text) + assert_equal "abc mno", @empty_document.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| - assert_equal "start finish", Article.parse_non_direct_links(wiki_text) - assert_equal "start finish", Article.parse_wiki_text(wiki_text) + assert_equal "start finish", @empty_document.parse_non_direct_links(wiki_text) + assert_equal "start finish", @empty_document.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text document_text = "[[en:Wikipedia]]" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" - Article.parse_text_document(document_text, repository, markup) + parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] - results = Article.parse_text_document(document_text, repository, markup) + results = parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end #Test whether the parser can handle non-ASCII text def test_non_ascii_text repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] phrases.each do |phrase| document_text = phrase - results = Article.parse_text_document(document_text, repository, markup) + results = parse_text_document(document_text, repository, markup) assert_equal 1, results.size, "Problem parsing #{phrase}" end end def test_redirect_target_and_sources misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") assert_equal correct_article, misspelled_article.redirect_target assert_not_equal unrelated_article, misspelled_article.redirect_target assert_nil correct_article.redirect_target assert_equal [misspelled_article], correct_article.redirect_sources assert_not_equal [unrelated_article], correct_article.redirect_sources assert_equal [], misspelled_article.redirect_sources end #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results def test_redirect_cleaning repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" misspelled_article = Article.find_by_title("Maria Theresa ov Austria") correct_article = Article.find_by_title("Maria Theresa of Austria") document_text_results_pairs = [] document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] #document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #This one should fail right now document_text_results_pairs.each do |document_text, expected_results| - actual_results = Article.parse_text_document(document_text, repository, markup) + actual_results = parse_text_document(document_text, repository, markup) assert_equal expected_results, actual_results end end + def parse_text_document(document_text, repository, markup) + document = Article.new_document(document_text, repository, markup) + return document.parse + end + end
agrimm/theweatherinlondon
da3f91cb11abe4b6231aac6cc3bd57353b922f59
Added redirect handling. Added local identifiers to articles. Trimmed some unit tests.
diff --git a/app/models/article.rb b/app/models/article.rb index a29335a..16dd23a 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,211 +1,240 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end + #If the article is a redirect, return the redirect target, else return nil + def redirect_target + if defined?(@redirect_target) + @redirect_target + else + results = Article.find_by_sql(["select articles.* from articles, redirects where redirects.redirect_source_repository_id = ? and redirects.redirect_source_local_id = ? and BINARY redirects.redirect_target_title = articles.title and redirects.redirect_source_repository_id = articles.repository_id", repository_id, local_id]) + raise "Can't happen case #{repository_id.to_s + " " + local_id.to_s} #{results.inject(""){|str, result| str + result.title + " " + result.repository_id.to_s} }" if results.size > 1 + @redirect_target = results.first + end + end + + def redirect_sources + if defined?(@redirect_sources) + @redirect_sources + else + #Table articles currently isn't indexed by repository_id and local_id, nor is table redirects indexed by redirect_target_title, so this would currently be slow + @redirect_sources = Article.find_by_sql(["select articles.* from articles, redirects where BINARY redirects.redirect_target_title = ? and redirects.redirect_source_repository_id = ? and redirects.redirect_source_repository_id = articles.repository_id and redirects.redirect_source_local_id = articles.local_id", title, repository_id]) + end + end + + def self.break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Determine if a phrase is boring #That is, it has one or zero non-boring words # and that the wiki text doesn't already link to it (if applicable) def self.phrase_is_boring?(phrase, existing_article_titles) #if existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( if existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? return true end words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def self.find_matching_articles(phrase, repository, existing_article_titles) return [] if phrase_is_boring?(phrase, existing_article_titles) articles = find(:all, :conditions => ["title = ? and repository_id = ?", phrase, repository], :limit => 1) articles end #Informs the caller if they should try a longer phrase than the current one in order to get a match def self.try_longer_phrase?(phrase, repository, existing_article_titles) if phrase_is_boring?(phrase, existing_article_titles) return true #Otherwise it chews up too much server time end potentially_matching_articles = find(:all, :conditions => ["title like ? and repository_id = ?", phrase + "%", repository], :limit=>1) return !potentially_matching_articles.empty? end #The main method called from the controller #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def self.parse_text_document(document_text, repository, markup) parse_results = [] words = break_up_phrase(document_text) raise(ArgumentError, "Document has too many words") if words.size > maximum_allowed_document_size if (markup == "auto-detect") markup = self.markup_autodetect(document_text) end if (markup == "mediawiki") wiki_text = document_text.dup parsed_wiki_text = self.parse_wiki_text(wiki_text) existing_article_titles = self.parse_existing_wiki_links(parsed_wiki_text) else existing_article_titles = [] end i = 0 while(true) j = 0 phrase = words[i + j] while(true) matching_articles = find_matching_articles(phrase, repository, existing_article_titles) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end break unless (try_longer_phrase?(phrase, repository, existing_article_titles) and i + j + 1 < words.size) j = j + 1 phrase += " " phrase += words[i + j] end break unless (i + 1 < words.size) i = i + 1 end cleaned_results = clean_results(parse_results) cleaned_results end #a method to get rid of the duplicate results + #to do: remove any results here that are redirects to existing wikified results def self.clean_results(parse_results) - parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant + #parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results + parse_results.uniq! cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] - if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one - is_non_duplicate_result = false - break - end + #if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one + # is_non_duplicate_result = false + # break + #end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end + + cleaned_results.delete_if do |phrase, matching_article| + cleaned_results.any? do |other_phrase, other_article| + matching_article.redirect_target == other_article + end + end cleaned_results end #Remove from MediaWiki text anything that is surrounded by <nowiki> def self.parse_nowiki(wiki_text) loop do #Delete anything paired by nowiki, non-greedily #Assumes that there aren't nested nowikis substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything within a template def self.parse_templates(wiki_text) loop do #Delete anything with paired {{ and }}, so long as no opening braces are inside #Should closing braces inside be forbidden as well? substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") break unless substitution_made end wiki_text end #Remove from MediaWiki text anything in an external link #This will remove the description of the link as well - for now def self.parse_external_links(wiki_text) #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") wiki_text end #Remove paired XHTML-style syntax def self.parse_paired_tags(wiki_text) #Remove paired tags wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') wiki_text end #Remove non-paired XHTML-style syntax def self.parse_unpaired_tags(wiki_text) wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") wiki_text end #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) def self.parse_non_direct_links(wiki_text) wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") wiki_text end #Remove from wiki_text anything that could confuse the program def self.parse_wiki_text(wiki_text) wiki_text = self.parse_nowiki(wiki_text) wiki_text = self.parse_templates(wiki_text) wiki_text = self.parse_paired_tags(wiki_text) wiki_text = self.parse_unpaired_tags(wiki_text) wiki_text = self.parse_non_direct_links(wiki_text) wiki_text = self.parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now wiki_text end #Look for existing wikilinks in a piece of text def self.parse_existing_wiki_links(wiki_text) unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) parsed_wiki_article_titles = [] unparsed_match_arrays.each do |unparsed_match_array| unparsed_title = unparsed_match_array.first parsed_title = unparsed_title.gsub(/_+/, " ") parsed_wiki_article_titles << parsed_title end parsed_wiki_article_titles.uniq end #Determine if the text is in some sort of markup def self.markup_autodetect(document_text) markup = "plain" if document_text =~ %r{\[\[[^\[\]]+\]\]}im markup = "mediawiki" end markup end end diff --git a/app/models/repository.rb b/app/models/repository.rb index 49124e5..dcfcfb1 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -1,14 +1,14 @@ class Repository < ActiveRecord::Base has_many :articles def generate_uri(article_title) require 'uri' underscored_title = article_title.gsub(" ", "_") - if (short_description == "English Wikipedia") - return URI.escape("http://en.wikipedia.org/wiki/" + underscored_title) + if (abbreviation =~ /(.*)wiki/) + return URI.escape("http://"+$1+".wikipedia.org/wiki/" + underscored_title) else raise "Unknown repository!" end end end diff --git a/db/migrate/005_article_recreation.rb b/db/migrate/005_article_recreation.rb new file mode 100644 index 0000000..4f4edd9 --- /dev/null +++ b/db/migrate/005_article_recreation.rb @@ -0,0 +1,15 @@ +#Fix timestamps, add field local_id for the local identifier the repository gave to an article +class ArticleRecreation < ActiveRecord::Migration + def self.up + Article.delete_all + add_column :articles, :local_id, :integer, :null =>true + add_column :articles, :created_at, :datetime + add_column :articles, :updated_at, :datetime + end + + def self.down + remove_column :articles, :updated_at + remove_column :articles, :created_at + remove_column :articles, :local_id + end +end diff --git a/db/migrate/006_add_redirect_table.rb b/db/migrate/006_add_redirect_table.rb new file mode 100644 index 0000000..8dd153f --- /dev/null +++ b/db/migrate/006_add_redirect_table.rb @@ -0,0 +1,19 @@ +class AddRedirectTable < ActiveRecord::Migration + def self.up + create_table :redirects, :id => false do |t| + t.integer "redirect_source_repository_id" + t.integer "redirect_source_local_id" + #There does not seem to be a need yet for redirects occur between repositories, so redirect_target_repository_id would be redundant + t.string "redirect_target_title" + t.datetime "created_at" + t.datetime "updated_at" + end + + add_index :redirects, [:redirect_source_repository_id, :redirect_source_local_id], :name=>'index_redirects_on_source' + add_index :redirects, [:redirect_source_repository_id, :redirect_target_title], :name=>'index_redirects_on_target' + end + + def self.down + drop_table "redirects" + end +end diff --git a/db/schema.rb b/db/schema.rb index 060b721..761c831 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,30 +1,44 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of ActiveRecord to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 4) do +ActiveRecord::Schema.define(:version => 6) do create_table "articles", :force => true do |t| - t.string "uri" - t.string "title" - t.integer "repository_id", :null => false + t.string "uri" + t.string "title" + t.integer "repository_id", :null => false + t.integer "local_id" + t.datetime "created_at" + t.datetime "updated_at" end add_index "articles", ["title"], :name => "index_articles_on_title" add_index "articles", ["uri"], :name => "index_articles_on_uri" + create_table "redirects", :id => false, :force => true do |t| + t.integer "redirect_source_repository_id" + t.integer "redirect_source_local_id" + t.string "redirect_target_title" + t.datetime "created_at" + t.datetime "updated_at" + end + + add_index "redirects", ["redirect_source_repository_id", "redirect_source_local_id"], :name => "index_redirects_on_source" + add_index "redirects", ["redirect_source_repository_id", "redirect_target_title"], :name => "index_redirects_on_target" + create_table "repositories", :force => true do |t| t.string "abbreviation" t.string "short_description" t.datetime "created_at" t.datetime "updated_at" end end diff --git a/test/fixtures/articles.yml b/test/fixtures/articles.yml index 514d871..3c90df1 100644 --- a/test/fixtures/articles.yml +++ b/test/fixtures/articles.yml @@ -1,13 +1,63 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html Maria Theresa of Austria: id: 1 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_of_Austria title: Maria Theresa of Austria repository_id: 1 + local_id: 1 Maria Theresa: id: 2 uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa title: Maria Theresa repository_id: 1 + local_id: 2 + +#ASCII, multiple capital letters +UAE in English: + id: 3 + uri: http://en.wikipedia.org/wiki/United_Arab_Emirates + title: United Arab Emirates + repository_id: 1 + local_id: 3 + +#ASCII, only one capital letter +Prime minister: + id: 4 + uri: http://en.wikipedia.org/wiki/Prime_minister + title: Prime minister + repository_id: 1 + local_id: 4 + +#Accented letter +Internet cafe: + id: 5 + uri: http://en.wikipedia.org/wiki/Internet_caf%C3%A9 + title: Internet caf<%= "\xc3\xa9"%> + repository_id: 1 + local_id: 5 + +#Arabic for internet cafe (I think) +Arabic internet cafe: + id: 6 + uri: http://ar.wikipedia.org/wiki/%D9%85%D9%82%D9%87%D9%89_%D8%A5%D9%86%D8%AA%D8%B1%D9%86%D8%AA + title: <%= "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA"%> + repository_id: 1 + local_id: 6 + +#Reversed string for internet cafe (I think) +Reversed arabic internet cafe: + id: 7 + uri: http://www.example.com/arabic_internet_cafe_reversed + title: <%= "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"%> + repository_id: 1 + local_id: 7 + +#Obviously a typo +Maria Thesa ov Austria: + id: 8 + uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_ov_Austria + title: Maria Theresa ov Austria + repository_id: 1 + local_id: 8 diff --git a/test/fixtures/redirects.yml b/test/fixtures/redirects.yml new file mode 100644 index 0000000..7f05b2c --- /dev/null +++ b/test/fixtures/redirects.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +redirect_1: + redirect_source_repository_id: 1 + redirect_source_local_id: 8 + redirect_target_title: Maria Theresa of Austria + diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 4160bfe..2364efd 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,146 +1,193 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles fixtures :repositories + fixtures :redirects # Replace this with your real tests. def test_truth assert true end - def test_clean_results + #The tests in this method may not make sense right now + def dont_test_clean_results repository = Repository.find(:first) article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end def test_parse_nowiki generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) end def test_parse_templates generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) end def test_parse_external_links generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) end def test_parse_paired_tags generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) end def test_parse_unpaired_tags generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) end def test_parse_non_direct_links generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) end #More generalized testing of syntax parsing #Assumptions: text is of a form # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text #and if parsing_removes_inner_section is true, it'll end up as # pre_syntax_text post_syntax_text #else # pre_syntax_text inside_syntax_text post_syntax_text def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] syntax_options = [ [syntax_start, syntax_finish], ["",""] ] inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] syntax_test_pairs = [] pre_syntax_options.each do |pre_syntax_option| syntax_options.each do |syntax_option| inside_syntax_options.each do |inside_syntax_option| post_syntax_options.each do |post_syntax_option| - syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" - syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" - unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option - if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) - #Don't remove the inside text - parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option - else - #Remove the inside text - parsed_text = pre_syntax_option + post_syntax_option + if rand < 0.04 + syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" + syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" + unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option + if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) + #Don't remove the inside text + parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option + else + #Remove the inside text + parsed_text = pre_syntax_option + post_syntax_option + end + syntax_test_pairs << [unparsed_text, parsed_text] end - syntax_test_pairs << [unparsed_text, parsed_text] end end end end syntax_test_pairs_duplicate = syntax_test_pairs.dup syntax_test_pairs_duplicate.each do |first_pair| syntax_test_pairs_duplicate.each do |second_pair| syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] end end syntax_test_pairs.each do |syntax_test_pair| unparsed_text = syntax_test_pair[0] parsed_text = syntax_test_pair[1] assert_equal parsed_text, Article.send(method_symbol, unparsed_text) end end def test_parse_existing_wiki_links wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" assert_equal ["London"], Article.parse_existing_wiki_links(wiki_text) end def test_nested_templates wiki_text = "abc {{def {{ghi}} jkl}} mno" assert_equal "abc mno", Article.parse_templates(wiki_text) end def test_trickier_non_direct_links wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] wiki_texts.each do |wiki_text| assert_equal "start finish", Article.parse_non_direct_links(wiki_text) assert_equal "start finish", Article.parse_wiki_text(wiki_text) end end def test_no_side_effects_on_document_text document_text = "[[en:Wikipedia]]" original_document_text = document_text.dup repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" Article.parse_text_document(document_text, repository, markup) assert_equal document_text, original_document_text end #Test that an article having the full title wikified deals with shortened versions of the title def test_handle_shorted_versions_of_wikified_titles repository = Repository.find_by_abbreviation("af-uncyclopedia") markup = "auto-detect" long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) document_text_results_pairs = [] document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] document_text_results_pairs.each do |document_text_results_pair| document_text = document_text_results_pair[0] expected_results = document_text_results_pair[1] results = Article.parse_text_document(document_text, repository, markup) assert_equal expected_results, results end end + + #Test whether the parser can handle non-ASCII text + def test_non_ascii_text + repository = Repository.find_by_abbreviation("af-uncyclopedia") + markup = "auto-detect" + phrases = ["United Arab Emirates", "Prime minister", "Internet caf\xc3\xa9", "\xD9\x85\xD9\x82\xD9\x87\xD9\x89 \xD8\xA5\xD9\x86\xD8\xAA\xD8\xB1\xD9\x86\xD8\xAA", "\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85"] + phrases.each do |phrase| + document_text = phrase + results = Article.parse_text_document(document_text, repository, markup) + assert_equal 1, results.size, "Problem parsing #{phrase}" + end + end + + def test_redirect_target_and_sources + misspelled_article = Article.find_by_title("Maria Theresa ov Austria") + correct_article = Article.find_by_title("Maria Theresa of Austria") + unrelated_article = Article.find_by_title("\xD8\xAA\xD9\x86\xD8\xB1\xD8\xAA\xD9\x86\xD8\xA5 \xD9\x89\xD9\x87\xD9\x82\xD9\x85") + assert_equal correct_article, misspelled_article.redirect_target + assert_not_equal unrelated_article, misspelled_article.redirect_target + assert_nil correct_article.redirect_target + + assert_equal [misspelled_article], correct_article.redirect_sources + assert_not_equal [unrelated_article], correct_article.redirect_sources + assert_equal [], misspelled_article.redirect_sources + end + + #Ensure that if article1 and article2 are mentioned in text, and article1 redirects to article2, then only article2 is found in the results + def test_redirect_cleaning + repository = Repository.find_by_abbreviation("af-uncyclopedia") + markup = "auto-detect" + misspelled_article = Article.find_by_title("Maria Theresa ov Austria") + correct_article = Article.find_by_title("Maria Theresa of Austria") + document_text_results_pairs = [] + document_text_results_pairs << [misspelled_article.title, [ [misspelled_article.title, misspelled_article] ] ] + document_text_results_pairs << [correct_article.title, [ [correct_article.title, correct_article] ] ] + document_text_results_pairs << ["#{misspelled_article.title} #{correct_article.title}", [ [correct_article.title, correct_article] ] ] + #document_text_results_pairs << ["[[#{correct_article.title}]] : #{misspelled_article.title} was born in", [ ] ] #This one should fail right now + document_text_results_pairs.each do |document_text, expected_results| + actual_results = Article.parse_text_document(document_text, repository, markup) + assert_equal expected_results, actual_results + end + end + end
agrimm/theweatherinlondon
ca0d3ffbf3db8dfc3cb63ddbb6974a712092975d
Added basic processing of wikitext, instructing the program to ignore links already wikified.
diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index 107eae5..f972015 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,30 +1,35 @@ class ReadController < ApplicationController def read @repository_choices = Repository.find(:all).map {|rc| [rc.short_description, rc.id]} + @markup_choices = [ ["Auto-detect (default)", "auto-detect"], ["MediaWiki formatting", "mediawiki"], ["Plain text", "plain"] ] if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end repository = Repository.find(params[:repository_id]) unless repository @errors << "Can't find repository" end + markup = params[:markup] + unless @markup_choices.map{|pair| pair.last}.include?(markup) + @errors << "Invalid markup choice" + end if @errors.empty? begin - @parse_results = Article.parse_text_document(document_text, repository) + @parse_results = Article.parse_text_document(document_text, repository, markup) rescue ArgumentError => error if error.message == "Document has too many words" @errors << "Please submit a text fewer than #{Article.maximum_allowed_document_size} words long" else raise end end end end end end diff --git a/app/models/article.rb b/app/models/article.rb index 7e773da..a29335a 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,113 +1,211 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size 15000 end #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end def self.break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Determine if a phrase is boring #That is, it has one or zero non-boring words - def self.phrase_is_boring?(phrase) + # and that the wiki text doesn't already link to it (if applicable) + def self.phrase_is_boring?(phrase, existing_article_titles) + #if existing_article_titles.any?{|existing_article_title| existing_article_title.chars.downcase.to_s.include?(phrase.chars.downcase)} #Unicode safe, too slow? :( + if existing_article_titles.any?{|existing_article_title| existing_article_title.downcase.include?(phrase.downcase)} #Not unicode safe? + return true + end words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| - number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) + number_non_boring_words += 1 unless boring_words.include?(word.downcase) #Not unicode safe? + #number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) #Unicode safe end return true unless number_non_boring_words > 1 end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case - def self.find_matching_articles(phrase, repository) - return [] if phrase_is_boring?(phrase) + def self.find_matching_articles(phrase, repository, existing_article_titles) + return [] if phrase_is_boring?(phrase, existing_article_titles) articles = find(:all, :conditions => ["title = ? and repository_id = ?", phrase, repository], :limit => 1) articles end #Informs the caller if they should try a longer phrase than the current one in order to get a match - def self.try_longer_phrase?(phrase, repository) - if phrase_is_boring?(phrase) + def self.try_longer_phrase?(phrase, repository, existing_article_titles) + if phrase_is_boring?(phrase, existing_article_titles) return true #Otherwise it chews up too much server time end potentially_matching_articles = find(:all, :conditions => ["title like ? and repository_id = ?", phrase + "%", repository], :limit=>1) return !potentially_matching_articles.empty? end + #The main method called from the controller #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words - def self.parse_text_document(document_text, repository) + def self.parse_text_document(document_text, repository, markup) parse_results = [] words = break_up_phrase(document_text) raise(ArgumentError, "Document has too many words") if words.size > maximum_allowed_document_size + if (markup == "auto-detect") + markup = self.markup_autodetect(document_text) + end + if (markup == "mediawiki") + wiki_text = document_text.dup + parsed_wiki_text = self.parse_wiki_text(wiki_text) + existing_article_titles = self.parse_existing_wiki_links(parsed_wiki_text) + else + existing_article_titles = [] + end i = 0 while(true) j = 0 phrase = words[i + j] while(true) - matching_articles = find_matching_articles(phrase, repository) + matching_articles = find_matching_articles(phrase, repository, existing_article_titles) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end - break unless (try_longer_phrase?(phrase, repository) and i + j + 1 < words.size) + break unless (try_longer_phrase?(phrase, repository, existing_article_titles) and i + j + 1 < words.size) j = j + 1 phrase += " " phrase += words[i + j] end break unless (i + 1 < words.size) i = i + 1 end cleaned_results = clean_results(parse_results) cleaned_results end #a method to get rid of the duplicate results def self.clean_results(parse_results) - parse_results.delete_if {|x| !(x[0].include?(" ") )} + parse_results.delete_if {|x| !(x[0].include?(" ") )} #This line may be redundant #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one is_non_duplicate_result = false break end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results end + #Remove from MediaWiki text anything that is surrounded by <nowiki> + def self.parse_nowiki(wiki_text) + loop do + #Delete anything paired by nowiki, non-greedily + #Assumes that there aren't nested nowikis + substitution_made = wiki_text.gsub!(%r{<nowiki>(.*?)</nowiki>}im,"") + break unless substitution_made + end + wiki_text + end + + #Remove from MediaWiki text anything within a template + def self.parse_templates(wiki_text) + loop do + #Delete anything with paired {{ and }}, so long as no opening braces are inside + #Should closing braces inside be forbidden as well? + substitution_made = wiki_text.gsub!(%r{\{\{([^\{]*?)\}\}}im,"") + break unless substitution_made + end + wiki_text + end + + #Remove from MediaWiki text anything in an external link + #This will remove the description of the link as well - for now + def self.parse_external_links(wiki_text) + #Delete everything starting with an opening square bracket, continuing with non-bracket characters until a colon, then any characters until it reaches a closing square bracket + wiki_text.gsub!(%r{\[[^\[]+?:[^\[]*?\]}im, "") + wiki_text + end + + #Remove paired XHTML-style syntax + def self.parse_paired_tags(wiki_text) + #Remove paired tags + wiki_text.gsub!(%r{<([a-zA-Z]*)>(.*?)</\1>}im, '\2') + wiki_text + end + + #Remove non-paired XHTML-style syntax + def self.parse_unpaired_tags(wiki_text) + wiki_text.gsub!(%r{<[a-zA-Z]*/>}im, "") + wiki_text + end + + #Remove links to other namespaces (eg [[Wikipedia:Manual of Style]]) , to media (eg [[Image:Wiki.png]]) and to other wikis (eg [[es:Plancton]]) + def self.parse_non_direct_links(wiki_text) + wiki_text.gsub!(%r{\[\[[^\[\]]*?:([^\[]|\[\[[^\[]*\]\])*?\]\]}im, "") + wiki_text + end + + #Remove from wiki_text anything that could confuse the program + def self.parse_wiki_text(wiki_text) + wiki_text = self.parse_nowiki(wiki_text) + wiki_text = self.parse_templates(wiki_text) + wiki_text = self.parse_paired_tags(wiki_text) + wiki_text = self.parse_unpaired_tags(wiki_text) + wiki_text = self.parse_non_direct_links(wiki_text) + wiki_text = self.parse_external_links(wiki_text) #Has to come after parse_non_direct_links for now + wiki_text + end + + #Look for existing wikilinks in a piece of text + def self.parse_existing_wiki_links(wiki_text) + unparsed_match_arrays = wiki_text.scan(%r{\[\[([^\]\#\|]*)([^\]]*?)\]\]}im) + parsed_wiki_article_titles = [] + unparsed_match_arrays.each do |unparsed_match_array| + unparsed_title = unparsed_match_array.first + parsed_title = unparsed_title.gsub(/_+/, " ") + parsed_wiki_article_titles << parsed_title + end + parsed_wiki_article_titles.uniq + end + + #Determine if the text is in some sort of markup + def self.markup_autodetect(document_text) + markup = "plain" + if document_text =~ %r{\[\[[^\[\]]+\]\]}im + markup = "mediawiki" + end + markup + end + end diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index e71a653..f09f91f 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,49 +1,51 @@ <% unless @errors.blank? %> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> <p>(Maximum <%= Article.maximum_allowed_document_size %> words)</p> <% form_tag(:action => :read) do %> <table> -<tr><td colspan=2> <%= text_area_tag(:document_text, params[:document_text], :cols=> 80, :rows=> 10) %></td></tr> +<tr><td colspan=2> <%= text_area_tag(:document_text, h(params[:document_text]), :cols=> 80, :rows=> 10) %></td></tr> <tr><td>Web site:</td> <td><%= select_tag "repository_id", options_for_select(@repository_choices) %></td></tr> +<tr><td>Markup (if any)</td> +<td><%= select_tag "markup", options_for_select(@markup_choices) %></td></tr> <tr><td> <%= submit_tag("Submit text") %> </td><td></td></tr> </table> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %> <H2>How to use The Weather in London</H2> <p>The Weather in London provides a different kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> <p>For example, if you submitted <a href="http://en.wikinews.org/wiki/Last_Titan_launch_complex_at_Cape_Canaveral_demolished">this block of text</a></p> <blockquote>Launch Complex 40 (LC-40) at the Cape Canaveral Air Force Station, Merritt Island, Florida has been demolished. The Mobile Service Structure (MSS), which was once used to load payloads onto Titan III and Titan IV rockets, was toppled by explosive charges at 13:00 GMT.</blockquote> <p>you would discover that Wikipedia has articles on Launch Complex, Cape Canaveral Air Force Station, Merritt Island, Titan III and Titan IV.</p> <p>You can also choose to see if a block of text contains a person or electorate in the <a href="http://en.wikipedia.org/wiki/Australian_House_of_Representatives">Australian House of Representatives</a>. This is possibly of marginal utility, but is an example of this concept not just applying for wikis.</p> <p>Currently, only phrases with more than one non-trivial word are checked, rather than single words, to reduce clutter.</p> diff --git a/config/deploy.example.rb b/config/deploy.example.rb new file mode 100644 index 0000000..31b7b5f --- /dev/null +++ b/config/deploy.example.rb @@ -0,0 +1,32 @@ +require 'mongrel_cluster/recipes' + +set :application, "weatherinlondon" +set :repository, "https://theweatherinlondon.googlecode.com/svn/trunk/" + +set :user, "sample_user_name" + +# If you aren't deploying to /u/apps/#{application} on the target +# servers (which is the default), you can specify the actual location +# via the :deploy_to variable: +set :deploy_to, "/home/#{user}/#{application}" + +set :deploy_via, :export + +# If you aren't using Subversion to manage your source code, specify +# your SCM below: +# set :scm, :subversion + +#No mongrel cluster available +#set :mongrel_conf, "#{current_path}/config/mongrel_cluster.yml" + +set :symlink_commands, "ln -nfs #{deploy_to}/#{shared_dir}/config/database.yml #{release_path}/config/database.yml" + +role :app, "theweatherinlondon.com" +role :web, "theweatherinlondon.com" +role :db, "theweatherinlondon.com", :primary => true + +#Courtesy of paulhammond.org and also pragmatic deployment, how to deal with database.yml and friends +desc "link in production database credentials, and other similar files" +task :after_update_code do + run "#{symlink_commands}" +end diff --git a/test/fixtures/articles.yml b/test/fixtures/articles.yml index b49c4eb..514d871 100644 --- a/test/fixtures/articles.yml +++ b/test/fixtures/articles.yml @@ -1,5 +1,13 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html -one: + +Maria Theresa of Austria: id: 1 -two: + uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa_of_Austria + title: Maria Theresa of Austria + repository_id: 1 + +Maria Theresa: id: 2 + uri: http://af.uncyclopedia.wikia.com/wiki/Maria_Theresa + title: Maria Theresa + repository_id: 1 diff --git a/test/fixtures/repositories.yml b/test/fixtures/repositories.yml index 5bf0293..2dce3ee 100644 --- a/test/fixtures/repositories.yml +++ b/test/fixtures/repositories.yml @@ -1,7 +1,7 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html -# one: -# column: value -# -# two: -# column: value +#An uncyclopedia language that does not yet exist +Afrikaans_uncyclopedia: + id: 1 + abbreviation: af-uncyclopedia + short_description: "Afrikaans Uncyclopedia" diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index f0bda8b..4160bfe 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -1,23 +1,146 @@ require File.dirname(__FILE__) + '/../test_helper' class ArticleTest < Test::Unit::TestCase fixtures :articles + fixtures :repositories # Replace this with your real tests. def test_truth assert true end def test_clean_results - article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1") - article2 = Article.create!(:title=> "b", :uri=>"http://www.exampel.com/2") + repository = Repository.find(:first) + article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1", :repository=>repository) + article2 = Article.create!(:title=> "b", :uri=>"http://www.example.com/2", :repository=>repository) identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(identical_results) assert identical_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] cleaned_results = Article.clean_results(containing_results) assert containing_results.size == 2, "Wrong number of original items" assert cleaned_results.size == 1, "Wrong number of final items" end + + def test_parse_nowiki + generalized_syntax_parsing_testing(:parse_nowiki, "<nowiki>", "</nowiki>", true) + generalized_syntax_parsing_testing(:parse_wiki_text, "<nowiki>", "</nowiki>", true) + end + + def test_parse_templates + generalized_syntax_parsing_testing(:parse_templates, "{{", "}}", true) + generalized_syntax_parsing_testing(:parse_wiki_text, "{{", "}}", true) + end + + def test_parse_external_links + generalized_syntax_parsing_testing(:parse_external_links, "[http://www.example.com", "]", true) + generalized_syntax_parsing_testing(:parse_wiki_text, "[http://www.example.com", "]", true) + end + + def test_parse_paired_tags + generalized_syntax_parsing_testing(:parse_paired_tags, "<ref>", "</ref>", false) + generalized_syntax_parsing_testing(:parse_wiki_text, "<ref>", "</ref>", false) + end + + def test_parse_unpaired_tags + generalized_syntax_parsing_testing(:parse_unpaired_tags, "<references/>", nil, false) + generalized_syntax_parsing_testing(:parse_wiki_text, "<references/>", nil, false) + end + + def test_parse_non_direct_links + generalized_syntax_parsing_testing(:parse_non_direct_links, "[[fr:", "]]", true) + generalized_syntax_parsing_testing(:parse_wiki_text, "[[fr:", "]]", true) + end + + #More generalized testing of syntax parsing + #Assumptions: text is of a form + # pre_syntax_text SYNTAX_START inside_syntax_text SYNTAX_FINISH post_syntax_text + #and if parsing_removes_inner_section is true, it'll end up as + # pre_syntax_text post_syntax_text + #else + # pre_syntax_text inside_syntax_text post_syntax_text + def generalized_syntax_parsing_testing(method_symbol, syntax_start, syntax_finish, parsing_removes_inner_section) + pre_syntax_options = ["Internationalization\nLocalization\n", " Internationalization ", "Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ","Hello: ", "[[Innocent bystander]]"] + syntax_options = [ [syntax_start, syntax_finish], ["",""] ] + inside_syntax_options = ["http://www.example.com", "Multi\nLine\nExample\n"] + post_syntax_options = ["Iñtërnâtiônàlizætiøn", " Iñtërnâtiônàlizætiøn ", " This is Iñtërnâtiônàlizætiøn (ie ǧø ĉȑȧẓẙ with the umlauts!?!). ", "Hello: ", "[[Innocent bystander]]"] + syntax_test_pairs = [] + pre_syntax_options.each do |pre_syntax_option| + syntax_options.each do |syntax_option| + inside_syntax_options.each do |inside_syntax_option| + post_syntax_options.each do |post_syntax_option| + syntax_start_option = syntax_option[0] || "" #May be syntax_start, or may be "" + syntax_finish_option = syntax_option[1] || "" #May be syntax_finish, or may be "" + unparsed_text = pre_syntax_option + syntax_start_option + inside_syntax_option + syntax_finish_option + post_syntax_option + if (not (parsing_removes_inner_section) or (syntax_start_option.blank? and syntax_finish_option.blank?) ) + #Don't remove the inside text + parsed_text = pre_syntax_option + inside_syntax_option + post_syntax_option + else + #Remove the inside text + parsed_text = pre_syntax_option + post_syntax_option + end + syntax_test_pairs << [unparsed_text, parsed_text] + end + end + end + end + syntax_test_pairs_duplicate = syntax_test_pairs.dup + syntax_test_pairs_duplicate.each do |first_pair| + syntax_test_pairs_duplicate.each do |second_pair| + syntax_test_pairs << [first_pair[0] + second_pair[0], first_pair[1] + second_pair[1] ] + end + end + syntax_test_pairs.each do |syntax_test_pair| + unparsed_text = syntax_test_pair[0] + parsed_text = syntax_test_pair[1] + assert_equal parsed_text, Article.send(method_symbol, unparsed_text) + end + end + + def test_parse_existing_wiki_links + wiki_text = "The rain in [[London]] is quite [[London#climate|wet]]" + assert_equal ["London"], Article.parse_existing_wiki_links(wiki_text) + end + + def test_nested_templates + wiki_text = "abc {{def {{ghi}} jkl}} mno" + assert_equal "abc mno", Article.parse_templates(wiki_text) + end + + def test_trickier_non_direct_links + wiki_texts = ["start [[Image:wiki.png]]finish", "start[[Image:wiki.png|The logo of this [[wiki]]]] finish", "start[[:Image:wiki.png|The logo of this [[wiki]], which is the English Wikipedia]] finish"] + wiki_texts.each do |wiki_text| + assert_equal "start finish", Article.parse_non_direct_links(wiki_text) + assert_equal "start finish", Article.parse_wiki_text(wiki_text) + end + end + + def test_no_side_effects_on_document_text + document_text = "[[en:Wikipedia]]" + original_document_text = document_text.dup + repository = Repository.find_by_abbreviation("af-uncyclopedia") + markup = "auto-detect" + Article.parse_text_document(document_text, repository, markup) + assert_equal document_text, original_document_text + end + + #Test that an article having the full title wikified deals with shortened versions of the title + def test_handle_shorted_versions_of_wikified_titles + repository = Repository.find_by_abbreviation("af-uncyclopedia") + markup = "auto-detect" + long_article = Article.find_by_title_and_repository_id("Maria Theresa of Austria", repository) + short_article = Article.find_by_title_and_repository_id("Maria Theresa", repository) + document_text_results_pairs = [] + document_text_results_pairs << ["#{long_article.title}", [ [long_article.title, long_article ] ] ] + document_text_results_pairs << ["[[#{long_article.title}]]", [ ] ] + document_text_results_pairs << ["#{long_article.title} : #{short_article.title} was born in", [ [long_article.title, long_article ] ] ] + document_text_results_pairs << ["[[#{long_article.title}]] : #{short_article.title} was born in", [ ] ] + document_text_results_pairs.each do |document_text_results_pair| + document_text = document_text_results_pair[0] + expected_results = document_text_results_pair[1] + results = Article.parse_text_document(document_text, repository, markup) + assert_equal expected_results, results + end + end end
agrimm/theweatherinlondon
7a54d935076ae8695ed7fd2a24b52f9b9206fa04
Added email address. Minor change.
diff --git a/app/views/layouts/read.rhtml b/app/views/layouts/read.rhtml index d6e416a..153847a 100644 --- a/app/views/layouts/read.rhtml +++ b/app/views/layouts/read.rhtml @@ -1,21 +1,21 @@ <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title>The Weather in London - Article Title Detection</title> <%= stylesheet_link_tag 'scaffold' %> </head> <body> <p style="color: green"><%= flash[:notice] %></p> <%= yield %> <H3>About this site</H3> -<p>This web site written by Andrew Grimm, coded in <a href="http://www.rubyonrails.org/">Ruby on Rails</a> and hosted by <a href="http://www.crucial.com.au/">Crucial Paradigm</a>. The source code is available <a href="http://code.google.com/p/theweatherinlondon/">here</a>.</p> +<p>This web site written by <a href="mailto:[email protected]">Andrew Grimm</a>, coded in <a href="http://www.rubyonrails.org/">Ruby on Rails</a> and hosted by <a href="http://www.crucial.com.au/">Crucial Paradigm</a>. The source code is available <a href="http://code.google.com/p/theweatherinlondon/">here</a>.</p> </body> </html>
agrimm/theweatherinlondon
8ce58ce53bd602e7da6075b82dba0b13d585f856
Changed maximum size of documents. Minor change.
diff --git a/app/models/article.rb b/app/models/article.rb index 415daaf..7e773da 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,113 +1,113 @@ class Article < ActiveRecord::Base validates_presence_of :title belongs_to :repository #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size - 500 + 15000 end #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else return repository.generate_uri(title) end end def self.break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Determine if a phrase is boring #That is, it has one or zero non-boring words def self.phrase_is_boring?(phrase) words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) end return true unless number_non_boring_words > 1 end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def self.find_matching_articles(phrase, repository) return [] if phrase_is_boring?(phrase) articles = find(:all, :conditions => ["title = ? and repository_id = ?", phrase, repository], :limit => 1) articles end #Informs the caller if they should try a longer phrase than the current one in order to get a match def self.try_longer_phrase?(phrase, repository) if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end potentially_matching_articles = find(:all, :conditions => ["title like ? and repository_id = ?", phrase + "%", repository], :limit=>1) return !potentially_matching_articles.empty? end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def self.parse_text_document(document_text, repository) parse_results = [] words = break_up_phrase(document_text) raise(ArgumentError, "Document has too many words") if words.size > maximum_allowed_document_size i = 0 while(true) j = 0 phrase = words[i + j] while(true) matching_articles = find_matching_articles(phrase, repository) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end break unless (try_longer_phrase?(phrase, repository) and i + j + 1 < words.size) j = j + 1 phrase += " " phrase += words[i + j] end break unless (i + 1 < words.size) i = i + 1 end cleaned_results = clean_results(parse_results) cleaned_results end #a method to get rid of the duplicate results def self.clean_results(parse_results) parse_results.delete_if {|x| !(x[0].include?(" ") )} #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one is_non_duplicate_result = false break end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results end end
agrimm/theweatherinlondon
8a199495d002619df65fe830ca87d08baf2adc92
Added capability to store information about more than one repository. Made web site look nicer. Added non-sensitive Capistrano files.
diff --git a/Capfile b/Capfile new file mode 100644 index 0000000..c36d48d --- /dev/null +++ b/Capfile @@ -0,0 +1,3 @@ +load 'deploy' if respond_to?(:namespace) # cap2 differentiator +Dir['vendor/plugins/*/recipes/*.rb'].each { |plugin| load(plugin) } +load 'config/deploy' \ No newline at end of file diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index 7633b8d..107eae5 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,25 +1,30 @@ class ReadController < ApplicationController def read + @repository_choices = Repository.find(:all).map {|rc| [rc.short_description, rc.id]} if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end + repository = Repository.find(params[:repository_id]) + unless repository + @errors << "Can't find repository" + end if @errors.empty? begin - @parse_results = Article.parse_text_document(document_text) + @parse_results = Article.parse_text_document(document_text, repository) rescue ArgumentError => error if error.message == "Document has too many words" @errors << "Please submit a text fewer than #{Article.maximum_allowed_document_size} words long" else raise end end end end end end diff --git a/app/models/article.rb b/app/models/article.rb index cbeb6e1..415daaf 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,114 +1,113 @@ class Article < ActiveRecord::Base validates_presence_of :title + belongs_to :repository #Return the maximum length a document should be, to avoid server resource issues def self.maximum_allowed_document_size - 50 + 500 end #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else - require 'uri' - underscored_title = title.gsub(" ", "_") - return URI.escape("http://en.wikipedia.org/wiki/" + underscored_title) + return repository.generate_uri(title) end end def self.break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Determine if a phrase is boring #That is, it has one or zero non-boring words def self.phrase_is_boring?(phrase) words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) end return true unless number_non_boring_words > 1 end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case - def self.find_matching_articles(phrase) + def self.find_matching_articles(phrase, repository) return [] if phrase_is_boring?(phrase) - articles = find(:all, :conditions => ["title = ?", phrase], :limit => 1) + articles = find(:all, :conditions => ["title = ? and repository_id = ?", phrase, repository], :limit => 1) articles end #Informs the caller if they should try a longer phrase than the current one in order to get a match - def self.try_longer_phrase?(phrase) + def self.try_longer_phrase?(phrase, repository) if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end - potentially_matching_articles = find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>1) + potentially_matching_articles = find(:all, :conditions => ["title like ? and repository_id = ?", phrase + "%", repository], :limit=>1) return !potentially_matching_articles.empty? end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words - def self.parse_text_document(document_text) + def self.parse_text_document(document_text, repository) parse_results = [] words = break_up_phrase(document_text) raise(ArgumentError, "Document has too many words") if words.size > maximum_allowed_document_size i = 0 while(true) j = 0 phrase = words[i + j] while(true) - matching_articles = find_matching_articles(phrase) + matching_articles = find_matching_articles(phrase, repository) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end - break unless (try_longer_phrase?(phrase) and i + j + 1 < words.size) + break unless (try_longer_phrase?(phrase, repository) and i + j + 1 < words.size) j = j + 1 phrase += " " phrase += words[i + j] end break unless (i + 1 < words.size) i = i + 1 end cleaned_results = clean_results(parse_results) cleaned_results end #a method to get rid of the duplicate results def self.clean_results(parse_results) parse_results.delete_if {|x| !(x[0].include?(" ") )} #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one is_non_duplicate_result = false break end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results end end diff --git a/app/models/repository.rb b/app/models/repository.rb new file mode 100644 index 0000000..49124e5 --- /dev/null +++ b/app/models/repository.rb @@ -0,0 +1,14 @@ +class Repository < ActiveRecord::Base + has_many :articles + + def generate_uri(article_title) + require 'uri' + underscored_title = article_title.gsub(" ", "_") + if (short_description == "English Wikipedia") + return URI.escape("http://en.wikipedia.org/wiki/" + underscored_title) + else + raise "Unknown repository!" + end + end + +end diff --git a/app/views/layouts/admin.rhtml b/app/views/layouts/read.rhtml similarity index 52% rename from app/views/layouts/admin.rhtml rename to app/views/layouts/read.rhtml index a1c79d3..d6e416a 100644 --- a/app/views/layouts/admin.rhtml +++ b/app/views/layouts/read.rhtml @@ -1,17 +1,21 @@ <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> - <title>Admin: <%= controller.action_name %></title> + <title>The Weather in London - Article Title Detection</title> <%= stylesheet_link_tag 'scaffold' %> </head> <body> <p style="color: green"><%= flash[:notice] %></p> <%= yield %> +<H3>About this site</H3> + +<p>This web site written by Andrew Grimm, coded in <a href="http://www.rubyonrails.org/">Ruby on Rails</a> and hosted by <a href="http://www.crucial.com.au/">Crucial Paradigm</a>. The source code is available <a href="http://code.google.com/p/theweatherinlondon/">here</a>.</p> + </body> </html> diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index 9e8a7a2..e71a653 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,43 +1,49 @@ <% unless @errors.blank? %> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> <p>(Maximum <%= Article.maximum_allowed_document_size %> words)</p> <% form_tag(:action => :read) do %> - <%= text_area_tag(:document_text, params[:document_text], :cols=> 50, :rows=> 10) %><br /> - <%= submit_tag("Submit text") %> +<table> +<tr><td colspan=2> <%= text_area_tag(:document_text, params[:document_text], :cols=> 80, :rows=> 10) %></td></tr> +<tr><td>Web site:</td> +<td><%= select_tag "repository_id", options_for_select(@repository_choices) %></td></tr> +<tr><td> <%= submit_tag("Submit text") %> </td><td></td></tr> +</table> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %> <H2>How to use The Weather in London</H2> -<p>The Weather in London provides a new kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> +<p>The Weather in London provides a different kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> -<p>For example, if you submitted</p> +<p>For example, if you submitted <a href="http://en.wikinews.org/wiki/Last_Titan_launch_complex_at_Cape_Canaveral_demolished">this block of text</a></p> <blockquote>Launch Complex 40 (LC-40) at the Cape Canaveral Air Force Station, Merritt Island, Florida has been demolished. The Mobile Service Structure (MSS), which was once used to load payloads onto Titan III and Titan IV rockets, was toppled by explosive charges at 13:00 GMT.</blockquote> <p>you would discover that Wikipedia has articles on Launch Complex, Cape Canaveral Air Force Station, Merritt Island, Titan III and Titan IV.</p> -<p>Currently, only phrases of words are checked, rather than single words to reduce clutter.</p> +<p>You can also choose to see if a block of text contains a person or electorate in the <a href="http://en.wikipedia.org/wiki/Australian_House_of_Representatives">Australian House of Representatives</a>. This is possibly of marginal utility, but is an example of this concept not just applying for wikis.</p> + +<p>Currently, only phrases with more than one non-trivial word are checked, rather than single words, to reduce clutter.</p> diff --git a/db/migrate/004_create_repositories.rb b/db/migrate/004_create_repositories.rb new file mode 100644 index 0000000..344f5ee --- /dev/null +++ b/db/migrate/004_create_repositories.rb @@ -0,0 +1,18 @@ +class CreateRepositories < ActiveRecord::Migration + def self.up + create_table :repositories do |t| + t.column :abbreviation, :string + t.column :short_description, :string + + t.timestamps + end + + add_column :articles, :repository_id, :integer, :null => false + end + + def self.down + remove_column :articles, :repository_id + + drop_table :repositories + end +end diff --git a/db/schema.rb b/db/schema.rb index 88ba2c5..060b721 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,15 +1,30 @@ -# This file is autogenerated. Instead of editing this file, please use the -# migrations feature of ActiveRecord to incrementally modify your database, and +# This file is auto-generated from the current state of the database. Instead of editing this file, +# please use the migrations feature of ActiveRecord to incrementally modify your database, and # then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your database schema. If you need +# to create the application database on another system, you should be using db:schema:load, not running +# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 3) do +ActiveRecord::Schema.define(:version => 4) do create_table "articles", :force => true do |t| - t.column "uri", :string - t.column "title", :string + t.string "uri" + t.string "title" + t.integer "repository_id", :null => false end add_index "articles", ["title"], :name => "index_articles_on_title" add_index "articles", ["uri"], :name => "index_articles_on_uri" + create_table "repositories", :force => true do |t| + t.string "abbreviation" + t.string "short_description" + t.datetime "created_at" + t.datetime "updated_at" + end + end diff --git a/public/stylesheets/scaffold.css b/public/stylesheets/scaffold.css index 8f239a3..61d1ff2 100644 --- a/public/stylesheets/scaffold.css +++ b/public/stylesheets/scaffold.css @@ -1,74 +1,70 @@ -body { background-color: #fff; color: #333; } +body { background-color: #E0FFFF; color: #333; } body, p, ol, ul, td { font-family: verdana, arial, helvetica, sans-serif; font-size: 13px; line-height: 18px; } pre { background-color: #eee; padding: 10px; font-size: 11px; } -a { color: #000; } -a:visited { color: #666; } -a:hover { color: #fff; background-color:#000; } - .fieldWithErrors { padding: 2px; background-color: red; display: table; } #errorExplanation { width: 400px; border: 2px solid red; padding: 7px; padding-bottom: 12px; margin-bottom: 20px; background-color: #f0f0f0; } #errorExplanation h2 { text-align: left; font-weight: bold; padding: 5px 5px 5px 15px; font-size: 12px; margin: -7px; background-color: #c00; color: #fff; } #errorExplanation p { color: #333; margin-bottom: 0; padding: 5px; } #errorExplanation ul li { font-size: 12px; list-style: square; } div.uploadStatus { margin: 5px; } div.progressBar { margin: 5px; } div.progressBar div.border { background-color: #fff; border: 1px solid grey; width: 100%; } div.progressBar div.background { background-color: #333; height: 18px; width: 0%; } diff --git a/test/fixtures/repositories.yml b/test/fixtures/repositories.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/repositories.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/unit/repository_test.rb b/test/unit/repository_test.rb new file mode 100644 index 0000000..0767cb8 --- /dev/null +++ b/test/unit/repository_test.rb @@ -0,0 +1,8 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class RepositoryTest < ActiveSupport::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end
agrimm/theweatherinlondon
6544285f298c604544277d63991df3f0db8e16e8
Eliminated default welcome page. Added instructions to web page.
diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index fa0d8ca..9e8a7a2 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,31 +1,43 @@ <% unless @errors.blank? %> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> <p>(Maximum <%= Article.maximum_allowed_document_size %> words)</p> <% form_tag(:action => :read) do %> <%= text_area_tag(:document_text, params[:document_text], :cols=> 50, :rows=> 10) %><br /> <%= submit_tag("Submit text") %> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %> + +<H2>How to use The Weather in London</H2> + +<p>The Weather in London provides a new kind of search. It allows people to submit a block of text, and see which phrases in it correspond to pages on a specific web site.</p> + +<p>For example, if you submitted</p> + +<blockquote>Launch Complex 40 (LC-40) at the Cape Canaveral Air Force Station, Merritt Island, Florida has been demolished. The Mobile Service Structure (MSS), which was once used to load payloads onto Titan III and Titan IV rockets, was toppled by explosive charges at 13:00 GMT.</blockquote> + +<p>you would discover that Wikipedia has articles on Launch Complex, Cape Canaveral Air Force Station, Merritt Island, Titan III and Titan IV.</p> + +<p>Currently, only phrases of words are checked, rather than single words to reduce clutter.</p> diff --git a/config/routes.rb b/config/routes.rb index 9bbc463..cc4b5a0 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,23 +1,23 @@ 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" + map.connect '', :controller => "read", :action=> "read" # Allow downloading Web Service WSDL as a file with an extension # instead of a file named 'wsdl' map.connect ':controller/service.wsdl', :action => 'wsdl' # Install the default route as the lowest priority. map.connect ':controller/:action/:id.:format' map.connect ':controller/:action/:id' end diff --git a/public/index.html b/public/index.html deleted file mode 100644 index a2daab7..0000000 --- a/public/index.html +++ /dev/null @@ -1,277 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html> - <head> - <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> - <title>Ruby on Rails: Welcome aboard</title> - <style type="text/css" media="screen"> - body { - margin: 0; - margin-bottom: 25px; - padding: 0; - background-color: #f0f0f0; - font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana"; - font-size: 13px; - color: #333; - } - - h1 { - font-size: 28px; - color: #000; - } - - a {color: #03c} - a:hover { - background-color: #03c; - color: white; - text-decoration: none; - } - - - #page { - background-color: #f0f0f0; - width: 750px; - margin: 0; - margin-left: auto; - margin-right: auto; - } - - #content { - float: left; - background-color: white; - border: 3px solid #aaa; - border-top: none; - padding: 25px; - width: 500px; - } - - #sidebar { - float: right; - width: 175px; - } - - #footer { - clear: both; - } - - - #header, #about, #getting-started { - padding-left: 75px; - padding-right: 30px; - } - - - #header { - background-image: url("images/rails.png"); - background-repeat: no-repeat; - background-position: top left; - height: 64px; - } - #header h1, #header h2 {margin: 0} - #header h2 { - color: #888; - font-weight: normal; - font-size: 16px; - } - - - #about h3 { - margin: 0; - margin-bottom: 10px; - font-size: 14px; - } - - #about-content { - background-color: #ffd; - border: 1px solid #fc0; - margin-left: -11px; - } - #about-content table { - margin-top: 10px; - margin-bottom: 10px; - font-size: 11px; - border-collapse: collapse; - } - #about-content td { - padding: 10px; - padding-top: 3px; - padding-bottom: 3px; - } - #about-content td.name {color: #555} - #about-content td.value {color: #000} - - #about-content.failure { - background-color: #fcc; - border: 1px solid #f00; - } - #about-content.failure p { - margin: 0; - padding: 10px; - } - - - #getting-started { - border-top: 1px solid #ccc; - margin-top: 25px; - padding-top: 15px; - } - #getting-started h1 { - margin: 0; - font-size: 20px; - } - #getting-started h2 { - margin: 0; - font-size: 14px; - font-weight: normal; - color: #333; - margin-bottom: 25px; - } - #getting-started ol { - margin-left: 0; - padding-left: 0; - } - #getting-started li { - font-size: 18px; - color: #888; - margin-bottom: 25px; - } - #getting-started li h2 { - margin: 0; - font-weight: normal; - font-size: 18px; - color: #333; - } - #getting-started li p { - color: #555; - font-size: 13px; - } - - - #search { - margin: 0; - padding-top: 10px; - padding-bottom: 10px; - font-size: 11px; - } - #search input { - font-size: 11px; - margin: 2px; - } - #search-text {width: 170px} - - - #sidebar ul { - margin-left: 0; - padding-left: 0; - } - #sidebar ul h3 { - margin-top: 25px; - font-size: 16px; - padding-bottom: 10px; - border-bottom: 1px solid #ccc; - } - #sidebar li { - list-style-type: none; - } - #sidebar ul.links li { - margin-bottom: 5px; - } - - </style> - <script type="text/javascript" src="javascripts/prototype.js"></script> - <script type="text/javascript" src="javascripts/effects.js"></script> - <script type="text/javascript"> - function about() { - if (Element.empty('about-content')) { - new Ajax.Updater('about-content', 'rails/info/properties', { - method: 'get', - onFailure: function() {Element.classNames('about-content').add('failure')}, - onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})} - }); - } else { - new Effect[Element.visible('about-content') ? - 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25}); - } - } - - window.onload = function() { - $('search-text').value = ''; - $('search').onsubmit = function() { - $('search-text').value = 'site:rubyonrails.org ' + $F('search-text'); - } - } - </script> - </head> - <body> - <div id="page"> - <div id="sidebar"> - <ul id="sidebar-items"> - <li> - <form id="search" action="http://www.google.com/search" method="get"> - <input type="hidden" name="hl" value="en" /> - <input type="text" id="search-text" name="q" value="site:rubyonrails.org " /> - <input type="submit" value="Search" /> the Rails site - </form> - </li> - - <li> - <h3>Join the community</h3> - <ul class="links"> - <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li> - <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li> - <li><a href="http://lists.rubyonrails.org/">Mailing lists</a></li> - <li><a href="http://wiki.rubyonrails.org/rails/pages/IRC">IRC channel</a></li> - <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li> - <li><a href="http://dev.rubyonrails.org/">Bug tracker</a></li> - </ul> - </li> - - <li> - <h3>Browse the documentation</h3> - <ul class="links"> - <li><a href="http://api.rubyonrails.org/">Rails API</a></li> - <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li> - <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li> - </ul> - </li> - </ul> - </div> - - <div id="content"> - <div id="header"> - <h1>Welcome aboard</h1> - <h2>You&rsquo;re riding the Rails!</h2> - </div> - - <div id="about"> - <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3> - <div id="about-content" style="display: none"></div> - </div> - - <div id="getting-started"> - <h1>Getting started</h1> - <h2>Here&rsquo;s how to get rolling:</h2> - - <ol> - <li> - <h2>Create your databases and edit <tt>config/database.yml</tt></h2> - <p>Rails needs to know your login and password.</p> - </li> - - <li> - <h2>Use <tt>script/generate</tt> to create your models and controllers</h2> - <p>To see all available options, run it without parameters.</p> - </li> - - <li> - <h2>Set up a default route and remove or rename this file</h2> - <p>Routes are setup in config/routes.rb.</p> - </li> - </ol> - </div> - </div> - - <div id="footer">&nbsp;</div> - </div> - </body> -</html> \ No newline at end of file
agrimm/theweatherinlondon
09b67c092106ab8018743f3712eff6cbf7f7d152
Added requirement for maximum document size. Added unicode handling to code. Reduced limits on results for article searching.
diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb index c900588..7633b8d 100644 --- a/app/controllers/read_controller.rb +++ b/app/controllers/read_controller.rb @@ -1,17 +1,25 @@ class ReadController < ApplicationController def read if request.post? @errors = [] if params[:document_text].blank? @errors << "Document text missing" else document_text = params[:document_text] end if @errors.empty? - @parse_results = Article.parse_text_document(document_text) + begin + @parse_results = Article.parse_text_document(document_text) + rescue ArgumentError => error + if error.message == "Document has too many words" + @errors << "Please submit a text fewer than #{Article.maximum_allowed_document_size} words long" + else + raise + end + end end end end end diff --git a/app/models/article.rb b/app/models/article.rb index b68f6b8..cbeb6e1 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,111 +1,114 @@ class Article < ActiveRecord::Base validates_presence_of :title + #Return the maximum length a document should be, to avoid server resource issues + def self.maximum_allowed_document_size + 50 + end + + #If a URI exists, return it, else dynamically generate it from the article title def get_uri unless self.uri == nil return self.uri else require 'uri' underscored_title = title.gsub(" ", "_") return URI.escape("http://en.wikipedia.org/wiki/" + underscored_title) end end def self.break_up_phrase(phrase) words = phrase.split(/[[:space:],.""'']+/) words end #Determine if a phrase is boring #That is, it has one or zero non-boring words def self.phrase_is_boring?(phrase) words = break_up_phrase(phrase) #count how many words are non-boring boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} number_non_boring_words = 0 words.each do |word| - number_non_boring_words += 1 unless boring_words.include?(word.downcase) + number_non_boring_words += 1 unless boring_words.include?(word.chars.downcase) end return true unless number_non_boring_words > 1 end #Return all articles that match the requested phrase #Probably should only return one article, but return an array just in case def self.find_matching_articles(phrase) return [] if phrase_is_boring?(phrase) - articles = find(:all, :conditions => ["title = ?", phrase]) + articles = find(:all, :conditions => ["title = ?", phrase], :limit => 1) articles end #Informs the caller if they should try a longer phrase than the current one in order to get a match def self.try_longer_phrase?(phrase) - if phrase.length < 6 or phrase_is_boring?(phrase) + if phrase_is_boring?(phrase) return true #Otherwise it chews up too much server time end - potentially_matching_articles = find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>2) + potentially_matching_articles = find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>1) return !potentially_matching_articles.empty? end #Read in a document, and return an array of phrases and their matching articles #Strategy: split into words, then iterate through the words def self.parse_text_document(document_text) parse_results = [] words = break_up_phrase(document_text) + raise(ArgumentError, "Document has too many words") if words.size > maximum_allowed_document_size i = 0 while(true) j = 0 phrase = words[i + j] while(true) matching_articles = find_matching_articles(phrase) matching_articles.each do |matching_article| parse_results << [phrase, matching_article] end break unless (try_longer_phrase?(phrase) and i + j + 1 < words.size) j = j + 1 phrase += " " phrase += words[i + j] end break unless (i + 1 < words.size) i = i + 1 end cleaned_results = clean_results(parse_results) cleaned_results end -#a method to get rid of the boring and duplicate results + #a method to get rid of the duplicate results def self.clean_results(parse_results) parse_results.delete_if {|x| !(x[0].include?(" ") )} #Get rid of results with a phrase shorter than another phrase in parse_results #Get rid of results with a phrase already included in cleaned_results - #I could use i and j, and include a parse_result i only if its phrase - # is not contained within any other parse_result's phrase, - #and if i's and j's phrase is the same, then only include if i is less than j cleaned_results = [] 0.upto(parse_results.size-1) do |i| is_non_duplicate_result = true current_result = parse_results[i] current_result_phrase = parse_results[i][0] 0.upto(parse_results.size-1) do |j| next if i == j other_result_phrase = parse_results[j][0] if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one is_non_duplicate_result = false break end if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) is_non_duplicate_result = false break end end if is_non_duplicate_result cleaned_results << current_result end end cleaned_results end - end diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml index 918571f..fa0d8ca 100644 --- a/app/views/read/read.rhtml +++ b/app/views/read/read.rhtml @@ -1,28 +1,31 @@ <% unless @errors.blank? %> <ul> <% for error in @errors %> <li><p><%= h(error) %></p></li> <% end %> </ul> <% end %> <H1>The Weather In London</H1> <H2>Submit text</H2> + +<p>(Maximum <%= Article.maximum_allowed_document_size %> words)</p> + <% form_tag(:action => :read) do %> <%= text_area_tag(:document_text, params[:document_text], :cols=> 50, :rows=> 10) %><br /> <%= submit_tag("Submit text") %> <% end %> <% if request.post? and @errors.blank? %> <H2>Matches found</H2> <ul> <% @parse_results.each do |parse_result| %> <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> <% end %> </ul> <H1>Original text</H1> <%= h(params[:document_text]).gsub("\n","<br />\n") %> <% end %>
agrimm/theweatherinlondon
403d240b64f682a5fe65bf3495896ff81f357db5
Got rid of boring Rails stuff.
diff --git a/config/database.example.yml b/config/database.example.yml index e610b20..c4e8b1b 100644 --- a/config/database.example.yml +++ b/config/database.example.yml @@ -1,36 +1,36 @@ # 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: # gem install mysql # Choose the win32 build. # Install MySQL and put its /bin directory on your path. # # 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: redcordial_development + database: theweatherinlondon_development username: nottherealusername password: nottherealpassword socket: /var/lib/mysql/mysql.sock # 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: redcordial_test + database: theweatherinlondon_test username: nottherealusername password: nottherealpassword socket: /var/lib/mysql/mysql.sock production: adapter: mysql - database: redcordial_production + database: theweatherinlondon_production username: nottherealusername password: nottherealpassword socket: /var/lib/mysql/mysql.sock diff --git a/log/development.log b/log/development.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/mongrel.log b/log/mongrel.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/production.log b/log/production.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/server.log b/log/server.log deleted file mode 100644 index e69de29..0000000 diff --git a/log/test.log b/log/test.log deleted file mode 100644 index e69de29..0000000
agrimm/theweatherinlondon
1a1b2cd971d4d0349cef2c9a4f5f3cd546ddba32
Initial import
diff --git a/README b/README new file mode 100644 index 0000000..0d6affd --- /dev/null +++ b/README @@ -0,0 +1,182 @@ +== Welcome to Rails + +Rails is a web-application and persistence framework that includes everything +needed to create database-backed web-applications according to the +Model-View-Control pattern of separation. This pattern splits the view (also +called the presentation) into "dumb" templates that are primarily responsible +for inserting pre-built data in between HTML tags. The model contains the +"smart" domain objects (such as Account, Product, Person, Post) that holds all +the business logic and knows how to persist themselves to a database. The +controller handles the incoming requests (such as Save New Account, Update +Product, Show Post) by manipulating the model and directing data to the view. + +In Rails, the model is handled by what's called an object-relational mapping +layer entitled Active Record. This layer allows you to present the data from +database rows as objects and embellish these data objects with business logic +methods. You can read more about Active Record in +link:files/vendor/rails/activerecord/README.html. + +The controller and view are handled by the Action Pack, which handles both +layers by its two parts: Action View and Action Controller. These two layers +are bundled in a single package due to their heavy interdependence. This is +unlike the relationship between the Active Record and Action Pack that is much +more separate. Each of these packages can be used independently outside of +Rails. You can read more about Action Pack in +link:files/vendor/rails/actionpack/README.html. + + +== Getting started + +1. At the command prompt, start a new rails application using the rails command + and your application name. Ex: rails myapp + (If you've downloaded rails in a complete tgz or zip, this step is already done) +2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options) +3. Go to http://localhost:3000/ and get "Welcome aboard: You’re riding the Rails!" +4. Follow the guidelines to start developing your application + + +== Web Servers + +By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise +Rails will use the WEBrick, the webserver that ships with Ruby. When you run script/server, +Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures +that you can always get up and running quickly. + +Mongrel is a Ruby-based webserver with a C-component (which requires compilation) that is +suitable for development and deployment of Rails applications. If you have Ruby Gems installed, +getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>. +More info at: http://mongrel.rubyforge.org + +If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than +Mongrel and WEBrick and also suited for production use, but requires additional +installation and currently only works well on OS X/Unix (Windows users are encouraged +to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from +http://www.lighttpd.net. + +And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby +web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not +for production. + +But of course its also possible to run Rails on any platform that supports FCGI. +Apache, LiteSpeed, IIS are just a few. For more information on FCGI, +please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI + + +== Debugging Rails + +Have "tail -f" commands running on the server.log and development.log. Rails will +automatically display debugging and runtime information to these files. Debugging +info will also be shown in the browser on requests from 127.0.0.1. + + +== Breakpoints + +Breakpoint support is available through the script/breakpointer client. This +means that you can break out of execution at any point in the code, investigate +and change the model, AND then resume execution! Example: + + class WeblogController < ActionController::Base + def index + @posts = Post.find(:all) + breakpoint "Breaking out from the list" + end + end + +So the controller will accept the action, run the first line, then present you +with a IRB prompt in the breakpointer window. Here you can do things like: + +Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint' + + >> @posts.inspect + => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, + #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" + >> @posts.first.title = "hello from a breakpoint" + => "hello from a breakpoint" + +...and even better is that you can examine how your runtime objects actually work: + + >> f = @posts.first + => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> + >> f. + Display all 152 possibilities? (y or n) + +Finally, when you're ready to resume execution, you press CTRL-D + + +== Console + +You can interact with the domain model by starting the console through <tt>script/console</tt>. +Here you'll have all parts of the application configured, just like it is when the +application is running. You can inspect domain models, change values, and save to the +database. Starting the script without arguments will launch it in the development environment. +Passing an argument will specify a different environment, like <tt>script/console production</tt>. + +To reload your controllers and models after launching the console run <tt>reload!</tt> + +To reload your controllers and models after launching the console run <tt>reload!</tt> + + + +== Description of contents + +app + Holds all the code that's specific to this particular application. + +app/controllers + Holds controllers that should be named like weblogs_controller.rb for + automated URL mapping. All controllers should descend from ApplicationController + which itself descends from ActionController::Base. + +app/models + Holds models that should be named like post.rb. + Most models will descend from ActiveRecord::Base. + +app/views + Holds the template files for the view that should be named like + weblogs/index.rhtml for the WeblogsController#index action. All views use eRuby + syntax. + +app/views/layouts + Holds the template files for layouts to be used with views. This models the common + header/footer method of wrapping views. In your views, define a layout using the + <tt>layout :default</tt> and create a file named default.rhtml. Inside default.rhtml, + call <% yield %> to render the view using this layout. + +app/helpers + Holds view helpers that should be named like weblogs_helper.rb. These are generated + for you automatically when using script/generate for controllers. Helpers can be used to + wrap functionality for your views into methods. + +config + Configuration files for the Rails environment, the routing map, the database, and other dependencies. + +components + Self-contained mini-applications that can bundle together controllers, models, and views. + +db + Contains the database schema in schema.rb. db/migrate contains all + the sequence of Migrations for your schema. + +doc + This directory is where your application documentation will be stored when generated + using <tt>rake doc:app</tt> + +lib + Application specific libraries. Basically, any kind of custom code that doesn't + belong under controllers, models, or helpers. This directory is in the load path. + +public + The directory available for the web server. Contains subdirectories for images, stylesheets, + and javascripts. Also contains the dispatchers and the default HTML files. This should be + set as the DOCUMENT_ROOT of your web server. + +script + Helper scripts for automation and generation. + +test + Unit and functional tests along with fixtures. When using the script/generate scripts, template + test files will be generated for you and placed in this directory. + +vendor + External libraries that the application depends on. Also includes the plugins subdirectory. + This directory is in the load path. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..3bb0e85 --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require(File.join(File.dirname(__FILE__), 'config', 'boot')) + +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +require 'tasks/rails' diff --git a/app/controllers/application.rb b/app/controllers/application.rb new file mode 100644 index 0000000..079a03f --- /dev/null +++ b/app/controllers/application.rb @@ -0,0 +1,7 @@ +# Filters added to this controller apply to all controllers in the application. +# Likewise, all the methods added will be available for all controllers. + +class ApplicationController < ActionController::Base + # Pick a unique cookie name to distinguish our session data from others' + session :session_key => '_redcordial_session_id' +end diff --git a/app/controllers/read_controller.rb b/app/controllers/read_controller.rb new file mode 100644 index 0000000..c900588 --- /dev/null +++ b/app/controllers/read_controller.rb @@ -0,0 +1,17 @@ +class ReadController < ApplicationController + + def read + if request.post? + @errors = [] + if params[:document_text].blank? + @errors << "Document text missing" + else + document_text = params[:document_text] + end + if @errors.empty? + @parse_results = Article.parse_text_document(document_text) + end + end + end + +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 0000000..22a7940 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,3 @@ +# Methods added to this helper will be available to all templates in the application. +module ApplicationHelper +end diff --git a/app/helpers/read_helper.rb b/app/helpers/read_helper.rb new file mode 100644 index 0000000..20f4bf9 --- /dev/null +++ b/app/helpers/read_helper.rb @@ -0,0 +1,2 @@ +module ReadHelper +end diff --git a/app/models/article.rb b/app/models/article.rb new file mode 100644 index 0000000..b68f6b8 --- /dev/null +++ b/app/models/article.rb @@ -0,0 +1,111 @@ +class Article < ActiveRecord::Base + validates_presence_of :title + + def get_uri + unless self.uri == nil + return self.uri + else + require 'uri' + underscored_title = title.gsub(" ", "_") + return URI.escape("http://en.wikipedia.org/wiki/" + underscored_title) + end + end + + def self.break_up_phrase(phrase) + words = phrase.split(/[[:space:],.""'']+/) + words + end + + #Determine if a phrase is boring + #That is, it has one or zero non-boring words + def self.phrase_is_boring?(phrase) + words = break_up_phrase(phrase) + #count how many words are non-boring + boring_words = %w{a and also are be been for get has in is just me of on only see than this the there was january february march april may june july august september october november december} + number_non_boring_words = 0 + words.each do |word| + number_non_boring_words += 1 unless boring_words.include?(word.downcase) + end + return true unless number_non_boring_words > 1 + end + + #Return all articles that match the requested phrase + #Probably should only return one article, but return an array just in case + def self.find_matching_articles(phrase) + return [] if phrase_is_boring?(phrase) + articles = find(:all, :conditions => ["title = ?", phrase]) + articles + end + + #Informs the caller if they should try a longer phrase than the current one in order to get a match + def self.try_longer_phrase?(phrase) + if phrase.length < 6 or phrase_is_boring?(phrase) + return true #Otherwise it chews up too much server time + end + potentially_matching_articles = find(:all, :conditions => ["title like ?", phrase + "%"], :limit=>2) + return !potentially_matching_articles.empty? + end + + #Read in a document, and return an array of phrases and their matching articles + #Strategy: split into words, then iterate through the words + def self.parse_text_document(document_text) + parse_results = [] + words = break_up_phrase(document_text) + i = 0 + while(true) + j = 0 + phrase = words[i + j] + while(true) + matching_articles = find_matching_articles(phrase) + matching_articles.each do |matching_article| + parse_results << [phrase, matching_article] + end + + break unless (try_longer_phrase?(phrase) and i + j + 1 < words.size) + j = j + 1 + phrase += " " + phrase += words[i + j] + end + + break unless (i + 1 < words.size) + i = i + 1 + end + + cleaned_results = clean_results(parse_results) + cleaned_results + end + +#a method to get rid of the boring and duplicate results + def self.clean_results(parse_results) + parse_results.delete_if {|x| !(x[0].include?(" ") )} + #Get rid of results with a phrase shorter than another phrase in parse_results + #Get rid of results with a phrase already included in cleaned_results + #I could use i and j, and include a parse_result i only if its phrase + # is not contained within any other parse_result's phrase, + #and if i's and j's phrase is the same, then only include if i is less than j + cleaned_results = [] + 0.upto(parse_results.size-1) do |i| + is_non_duplicate_result = true + current_result = parse_results[i] + current_result_phrase = parse_results[i][0] + 0.upto(parse_results.size-1) do |j| + next if i == j + other_result_phrase = parse_results[j][0] + if current_result_phrase == other_result_phrase and i > j #Identical phrases, current result not the first one + is_non_duplicate_result = false + break + end + if other_result_phrase.size > current_result_phrase.size and other_result_phrase.include?(current_result_phrase) + is_non_duplicate_result = false + break + end + end + if is_non_duplicate_result + cleaned_results << current_result + end + end + cleaned_results + end + + +end diff --git a/app/views/layouts/admin.rhtml b/app/views/layouts/admin.rhtml new file mode 100644 index 0000000..a1c79d3 --- /dev/null +++ b/app/views/layouts/admin.rhtml @@ -0,0 +1,17 @@ +<!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" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Admin: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/app/views/read/read.rhtml b/app/views/read/read.rhtml new file mode 100644 index 0000000..918571f --- /dev/null +++ b/app/views/read/read.rhtml @@ -0,0 +1,28 @@ +<% unless @errors.blank? %> + <ul> + <% for error in @errors %> + <li><p><%= h(error) %></p></li> + <% end %> + </ul> +<% end %> + +<H1>The Weather In London</H1> + +<H2>Submit text</H2> +<% form_tag(:action => :read) do %> + <%= text_area_tag(:document_text, params[:document_text], :cols=> 50, :rows=> 10) %><br /> + <%= submit_tag("Submit text") %> +<% end %> + +<% if request.post? and @errors.blank? %> + <H2>Matches found</H2> + + <ul> + <% @parse_results.each do |parse_result| %> + <li><a href="<%= parse_result[1].get_uri %>"><%= h(parse_result[0]) %></a></li> + <% end %> + </ul> + + <H1>Original text</H1> + <%= h(params[:document_text]).gsub("\n","<br />\n") %> +<% end %> diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000..b7af0c3 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,45 @@ +# 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 =~ /(:?mswin|mingw)/ + 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 + # Asking for 1.1.6 will give you 1.1.6.5206, if available -- makes it easier to use beta gems + rails_gem = Gem.cache.search('rails', "~>#{version}.0").sort_by { |g| g.version.version }.last + + if rails_gem + gem "rails", "=#{rails_gem.version.version}" + require rails_gem.full_gem_path + '/lib/initializer' + else + STDERR.puts %(Cannot find gem for Rails ~>#{version}.0: + 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 + gem "rails" + require 'initializer' + end + end + + Rails::Initializer.run(:set_load_path) +end diff --git a/config/database.example.yml b/config/database.example.yml new file mode 100644 index 0000000..e610b20 --- /dev/null +++ b/config/database.example.yml @@ -0,0 +1,36 @@ +# 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: +# gem install mysql +# Choose the win32 build. +# Install MySQL and put its /bin directory on your path. +# +# 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: redcordial_development + username: nottherealusername + password: nottherealpassword + socket: /var/lib/mysql/mysql.sock + +# 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: redcordial_test + username: nottherealusername + password: nottherealpassword + socket: /var/lib/mysql/mysql.sock + +production: + adapter: mysql + database: redcordial_production + username: nottherealusername + password: nottherealpassword + socket: /var/lib/mysql/mysql.sock diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..5db2d3a --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,60 @@ +# 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.2.3' unless defined? RAILS_GEM_VERSION + +# 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 over those specified here + + # Skip frameworks you're not going to use (only works if using vendor/rails) + # config.frameworks -= [ :action_web_service, :action_mailer ] + + # Only load the plugins named here, by default all plugins in vendor/plugins are loaded + # config.plugins = %W( exception_notification ssl_requirement ) + + # 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 = :sql + + # 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 + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf +# Mime::Type.register "application/x-mobile", :mobile + +# Include your application configuration below \ No newline at end of file diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 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 100644 index 0000000..cb295b8 --- /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, bad email addresses will be ignored +# config.action_mailer.raise_delivery_errors = false diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 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 100644 index 0000000..9bbc463 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,23 @@ +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' + + # Install the default route as the lowest priority. + map.connect ':controller/:action/:id.:format' + map.connect ':controller/:action/:id' +end diff --git a/db/migrate/001_create_articles.rb b/db/migrate/001_create_articles.rb new file mode 100644 index 0000000..07ed28c --- /dev/null +++ b/db/migrate/001_create_articles.rb @@ -0,0 +1,12 @@ +class CreateArticles < ActiveRecord::Migration + def self.up + create_table :articles do |t| + t.column :uri, :string + t.column :title, :string + end + end + + def self.down + drop_table :articles + end +end diff --git a/db/migrate/002_add_test_articles.rb b/db/migrate/002_add_test_articles.rb new file mode 100644 index 0000000..fe6f618 --- /dev/null +++ b/db/migrate/002_add_test_articles.rb @@ -0,0 +1,11 @@ +class AddTestArticles < ActiveRecord::Migration + def self.up + self.down + #Article.create!(:uri => "http://en.wikipedia.org/wiki/Hello_world_program", :title => "Hello world program") + #Article.create!(:uri => "http://en.wikipedia.org/wiki/Wolbachia", :title => "Wolbachia") + end + + def self.down + Article.delete_all + end +end diff --git a/db/migrate/003_add_article_index.rb b/db/migrate/003_add_article_index.rb new file mode 100644 index 0000000..05a866d --- /dev/null +++ b/db/migrate/003_add_article_index.rb @@ -0,0 +1,11 @@ +class AddArticleIndex < ActiveRecord::Migration + def self.up + add_index :articles, :title + add_index :articles, :uri + end + + def self.down + remove_index :articles, :title + remove_index :articles, :uri + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..88ba2c5 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,15 @@ +# This file is autogenerated. Instead of editing this file, please use the +# migrations feature of ActiveRecord to incrementally modify your database, and +# then regenerate this schema definition. + +ActiveRecord::Schema.define(:version => 3) do + + create_table "articles", :force => true do |t| + t.column "uri", :string + t.column "title", :string + end + + add_index "articles", ["title"], :name => "index_articles_on_title" + add_index "articles", ["uri"], :name => "index_articles_on_uri" + +end diff --git a/doc/README_FOR_APP b/doc/README_FOR_APP new file mode 100644 index 0000000..ac6c149 --- /dev/null +++ b/doc/README_FOR_APP @@ -0,0 +1,2 @@ +Use this README file to introduce your application and point to useful places in the API for learning more. +Run "rake appdoc" to generate API documentation for your models and controllers. \ No newline at end of file diff --git a/log/development.log b/log/development.log new file mode 100644 index 0000000..e69de29 diff --git a/log/mongrel.log b/log/mongrel.log new file mode 100644 index 0000000..e69de29 diff --git a/log/production.log b/log/production.log new file mode 100644 index 0000000..e69de29 diff --git a/log/server.log b/log/server.log new file mode 100644 index 0000000..e69de29 diff --git a/log/test.log b/log/test.log new file mode 100644 index 0000000..e69de29 diff --git a/public/.htaccess b/public/.htaccess new file mode 100644 index 0000000..d3c9983 --- /dev/null +++ b/public/.htaccess @@ -0,0 +1,40 @@ +# General Apache options +AddHandler fastcgi-script .fcgi +AddHandler cgi-script .cgi +Options +FollowSymLinks +ExecCGI + +# If you don't want Rails to look in certain directories, +# use the following rewrite rules so that Apache won't rewrite certain requests +# +# Example: +# RewriteCond %{REQUEST_URI} ^/notrails.* +# RewriteRule .* - [L] + +# Redirect all requests not available on the filesystem to Rails +# By default the cgi dispatcher is used which is very slow +# +# For better performance replace the dispatcher with the fastcgi one +# +# Example: +# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] +RewriteEngine On + +# If your Rails application is accessed via an Alias directive, +# then you MUST also set the RewriteBase in this htaccess file. +# +# Example: +# Alias /myrailsapp /path/to/myrailsapp/public +# RewriteBase /myrailsapp + +RewriteRule ^$ index.html [QSA] +RewriteRule ^([^.]+)$ $1.html [QSA] +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule ^(.*)$ dispatch.cgi [QSA,L] + +# In case Rails experiences terminal errors +# Instead of displaying this message you can supply a file here which will be rendered instead +# +# Example: +# ErrorDocument 500 /500.html + +ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" \ No newline at end of file diff --git a/public/404.html b/public/404.html new file mode 100644 index 0000000..eff660b --- /dev/null +++ b/public/404.html @@ -0,0 +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" xml:lang="en" lang="en"> + +<head> + <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> + <title>The page you were looking for doesn't exist (404)</title> + <style type="text/css"> + body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; } + div.dialog { + width: 25em; + padding: 0 4em; + margin: 4em auto 0 auto; + border: 1px solid #ccc; + border-right-color: #999; + border-bottom-color: #999; + } + h1 { font-size: 100%; color: #f00; line-height: 1.5em; } + </style> +</head> + +<body> + <!-- This file lives in public/404.html --> + <div class="dialog"> + <h1>The page you were looking for doesn't exist.</h1> + <p>You may have mistyped the address or the page may have moved.</p> + </div> +</body> +</html> \ No newline at end of file diff --git a/public/500.html b/public/500.html new file mode 100644 index 0000000..f0aee0e --- /dev/null +++ b/public/500.html @@ -0,0 +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" xml:lang="en" lang="en"> + +<head> + <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> + <title>We're sorry, but something went wrong</title> + <style type="text/css"> + body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; } + div.dialog { + width: 25em; + padding: 0 4em; + margin: 4em auto 0 auto; + border: 1px solid #ccc; + border-right-color: #999; + border-bottom-color: #999; + } + h1 { font-size: 100%; color: #f00; line-height: 1.5em; } + </style> +</head> + +<body> + <!-- This file lives in public/500.html --> + <div class="dialog"> + <h1>We're sorry, but something went wrong.</h1> + <p>We've been notified about this issue and we'll take a look at it shortly.</p> + </div> +</body> +</html> \ No newline at end of file diff --git a/public/dispatch.cgi b/public/dispatch.cgi new file mode 100755 index 0000000..9730473 --- /dev/null +++ b/public/dispatch.cgi @@ -0,0 +1,10 @@ +#!/usr/bin/ruby + +require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) + +# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like: +# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired +require "dispatcher" + +ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun) +Dispatcher.dispatch \ No newline at end of file diff --git a/public/dispatch.fcgi b/public/dispatch.fcgi new file mode 100755 index 0000000..f934b30 --- /dev/null +++ b/public/dispatch.fcgi @@ -0,0 +1,24 @@ +#!/usr/bin/ruby +# +# You may specify the path to the FastCGI crash log (a log of unhandled +# exceptions which forced the FastCGI instance to exit, great for debugging) +# and the number of requests to process before running garbage collection. +# +# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log +# and the GC period is nil (turned off). A reasonable number of requests +# could range from 10-100 depending on the memory footprint of your app. +# +# Example: +# # Default log path, normal GC behavior. +# RailsFCGIHandler.process! +# +# # Default log path, 50 requests between GC. +# RailsFCGIHandler.process! nil, 50 +# +# # Custom log path, normal GC behavior. +# RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log' +# +require File.dirname(__FILE__) + "/../config/environment" +require 'fcgi_handler' + +RailsFCGIHandler.process! diff --git a/public/dispatch.rb b/public/dispatch.rb new file mode 100755 index 0000000..9730473 --- /dev/null +++ b/public/dispatch.rb @@ -0,0 +1,10 @@ +#!/usr/bin/ruby + +require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) + +# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like: +# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired +require "dispatcher" + +ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun) +Dispatcher.dispatch \ No newline at end of file diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/public/images/rails.png b/public/images/rails.png new file mode 100644 index 0000000..b8441f1 Binary files /dev/null and b/public/images/rails.png differ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..a2daab7 --- /dev/null +++ b/public/index.html @@ -0,0 +1,277 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> + <title>Ruby on Rails: Welcome aboard</title> + <style type="text/css" media="screen"> + body { + margin: 0; + margin-bottom: 25px; + padding: 0; + background-color: #f0f0f0; + font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana"; + font-size: 13px; + color: #333; + } + + h1 { + font-size: 28px; + color: #000; + } + + a {color: #03c} + a:hover { + background-color: #03c; + color: white; + text-decoration: none; + } + + + #page { + background-color: #f0f0f0; + width: 750px; + margin: 0; + margin-left: auto; + margin-right: auto; + } + + #content { + float: left; + background-color: white; + border: 3px solid #aaa; + border-top: none; + padding: 25px; + width: 500px; + } + + #sidebar { + float: right; + width: 175px; + } + + #footer { + clear: both; + } + + + #header, #about, #getting-started { + padding-left: 75px; + padding-right: 30px; + } + + + #header { + background-image: url("images/rails.png"); + background-repeat: no-repeat; + background-position: top left; + height: 64px; + } + #header h1, #header h2 {margin: 0} + #header h2 { + color: #888; + font-weight: normal; + font-size: 16px; + } + + + #about h3 { + margin: 0; + margin-bottom: 10px; + font-size: 14px; + } + + #about-content { + background-color: #ffd; + border: 1px solid #fc0; + margin-left: -11px; + } + #about-content table { + margin-top: 10px; + margin-bottom: 10px; + font-size: 11px; + border-collapse: collapse; + } + #about-content td { + padding: 10px; + padding-top: 3px; + padding-bottom: 3px; + } + #about-content td.name {color: #555} + #about-content td.value {color: #000} + + #about-content.failure { + background-color: #fcc; + border: 1px solid #f00; + } + #about-content.failure p { + margin: 0; + padding: 10px; + } + + + #getting-started { + border-top: 1px solid #ccc; + margin-top: 25px; + padding-top: 15px; + } + #getting-started h1 { + margin: 0; + font-size: 20px; + } + #getting-started h2 { + margin: 0; + font-size: 14px; + font-weight: normal; + color: #333; + margin-bottom: 25px; + } + #getting-started ol { + margin-left: 0; + padding-left: 0; + } + #getting-started li { + font-size: 18px; + color: #888; + margin-bottom: 25px; + } + #getting-started li h2 { + margin: 0; + font-weight: normal; + font-size: 18px; + color: #333; + } + #getting-started li p { + color: #555; + font-size: 13px; + } + + + #search { + margin: 0; + padding-top: 10px; + padding-bottom: 10px; + font-size: 11px; + } + #search input { + font-size: 11px; + margin: 2px; + } + #search-text {width: 170px} + + + #sidebar ul { + margin-left: 0; + padding-left: 0; + } + #sidebar ul h3 { + margin-top: 25px; + font-size: 16px; + padding-bottom: 10px; + border-bottom: 1px solid #ccc; + } + #sidebar li { + list-style-type: none; + } + #sidebar ul.links li { + margin-bottom: 5px; + } + + </style> + <script type="text/javascript" src="javascripts/prototype.js"></script> + <script type="text/javascript" src="javascripts/effects.js"></script> + <script type="text/javascript"> + function about() { + if (Element.empty('about-content')) { + new Ajax.Updater('about-content', 'rails/info/properties', { + method: 'get', + onFailure: function() {Element.classNames('about-content').add('failure')}, + onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})} + }); + } else { + new Effect[Element.visible('about-content') ? + 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25}); + } + } + + window.onload = function() { + $('search-text').value = ''; + $('search').onsubmit = function() { + $('search-text').value = 'site:rubyonrails.org ' + $F('search-text'); + } + } + </script> + </head> + <body> + <div id="page"> + <div id="sidebar"> + <ul id="sidebar-items"> + <li> + <form id="search" action="http://www.google.com/search" method="get"> + <input type="hidden" name="hl" value="en" /> + <input type="text" id="search-text" name="q" value="site:rubyonrails.org " /> + <input type="submit" value="Search" /> the Rails site + </form> + </li> + + <li> + <h3>Join the community</h3> + <ul class="links"> + <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li> + <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li> + <li><a href="http://lists.rubyonrails.org/">Mailing lists</a></li> + <li><a href="http://wiki.rubyonrails.org/rails/pages/IRC">IRC channel</a></li> + <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li> + <li><a href="http://dev.rubyonrails.org/">Bug tracker</a></li> + </ul> + </li> + + <li> + <h3>Browse the documentation</h3> + <ul class="links"> + <li><a href="http://api.rubyonrails.org/">Rails API</a></li> + <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li> + <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li> + </ul> + </li> + </ul> + </div> + + <div id="content"> + <div id="header"> + <h1>Welcome aboard</h1> + <h2>You&rsquo;re riding the Rails!</h2> + </div> + + <div id="about"> + <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3> + <div id="about-content" style="display: none"></div> + </div> + + <div id="getting-started"> + <h1>Getting started</h1> + <h2>Here&rsquo;s how to get rolling:</h2> + + <ol> + <li> + <h2>Create your databases and edit <tt>config/database.yml</tt></h2> + <p>Rails needs to know your login and password.</p> + </li> + + <li> + <h2>Use <tt>script/generate</tt> to create your models and controllers</h2> + <p>To see all available options, run it without parameters.</p> + </li> + + <li> + <h2>Set up a default route and remove or rename this file</h2> + <p>Routes are setup in config/routes.rb.</p> + </li> + </ol> + </div> + </div> + + <div id="footer">&nbsp;</div> + </div> + </body> +</html> \ No newline at end of file diff --git a/public/javascripts/application.js b/public/javascripts/application.js new file mode 100644 index 0000000..fe45776 --- /dev/null +++ b/public/javascripts/application.js @@ -0,0 +1,2 @@ +// Place your application-specific JavaScript functions and classes here +// This file is automatically included by javascript_include_tag :defaults diff --git a/public/javascripts/controls.js b/public/javascripts/controls.js new file mode 100644 index 0000000..8c273f8 --- /dev/null +++ b/public/javascripts/controls.js @@ -0,0 +1,833 @@ +// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan) +// (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com) +// Contributors: +// Richard Livsey +// Rahul Bhargava +// Rob Wills +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +// Autocompleter.Base handles all the autocompletion functionality +// that's independent of the data source for autocompletion. This +// includes drawing the autocompletion menu, observing keyboard +// and mouse events, and similar. +// +// Specific autocompleters need to provide, at the very least, +// a getUpdatedChoices function that will be invoked every time +// the text inside the monitored textbox changes. This method +// should get the text for which to provide autocompletion by +// invoking this.getToken(), NOT by directly accessing +// this.element.value. This is to allow incremental tokenized +// autocompletion. Specific auto-completion logic (AJAX, etc) +// belongs in getUpdatedChoices. +// +// Tokenized incremental autocompletion is enabled automatically +// when an autocompleter is instantiated with the 'tokens' option +// in the options parameter, e.g.: +// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' }); +// will incrementally autocomplete with a comma as the token. +// Additionally, ',' in the above example can be replaced with +// a token array, e.g. { tokens: [',', '\n'] } which +// enables autocompletion on multiple tokens. This is most +// useful when one of the tokens is \n (a newline), as it +// allows smart autocompletion after linebreaks. + +if(typeof Effect == 'undefined') + throw("controls.js requires including script.aculo.us' effects.js library"); + +var Autocompleter = {} +Autocompleter.Base = function() {}; +Autocompleter.Base.prototype = { + baseInitialize: function(element, update, options) { + this.element = $(element); + this.update = $(update); + this.hasFocus = false; + this.changed = false; + this.active = false; + this.index = 0; + this.entryCount = 0; + + if(this.setOptions) + this.setOptions(options); + else + this.options = options || {}; + + this.options.paramName = this.options.paramName || this.element.name; + this.options.tokens = this.options.tokens || []; + this.options.frequency = this.options.frequency || 0.4; + this.options.minChars = this.options.minChars || 1; + this.options.onShow = this.options.onShow || + function(element, update){ + if(!update.style.position || update.style.position=='absolute') { + update.style.position = 'absolute'; + Position.clone(element, update, { + setHeight: false, + offsetTop: element.offsetHeight + }); + } + Effect.Appear(update,{duration:0.15}); + }; + this.options.onHide = this.options.onHide || + function(element, update){ new Effect.Fade(update,{duration:0.15}) }; + + if(typeof(this.options.tokens) == 'string') + this.options.tokens = new Array(this.options.tokens); + + this.observer = null; + + this.element.setAttribute('autocomplete','off'); + + Element.hide(this.update); + + Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this)); + Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this)); + }, + + show: function() { + if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); + if(!this.iefix && + (navigator.appVersion.indexOf('MSIE')>0) && + (navigator.userAgent.indexOf('Opera')<0) && + (Element.getStyle(this.update, 'position')=='absolute')) { + new Insertion.After(this.update, + '<iframe id="' + this.update.id + '_iefix" '+ + 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' + + 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>'); + this.iefix = $(this.update.id+'_iefix'); + } + if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); + }, + + fixIEOverlapping: function() { + Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); + this.iefix.style.zIndex = 1; + this.update.style.zIndex = 2; + Element.show(this.iefix); + }, + + hide: function() { + this.stopIndicator(); + if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); + if(this.iefix) Element.hide(this.iefix); + }, + + startIndicator: function() { + if(this.options.indicator) Element.show(this.options.indicator); + }, + + stopIndicator: function() { + if(this.options.indicator) Element.hide(this.options.indicator); + }, + + onKeyPress: function(event) { + if(this.active) + switch(event.keyCode) { + case Event.KEY_TAB: + case Event.KEY_RETURN: + this.selectEntry(); + Event.stop(event); + case Event.KEY_ESC: + this.hide(); + this.active = false; + Event.stop(event); + return; + case Event.KEY_LEFT: + case Event.KEY_RIGHT: + return; + case Event.KEY_UP: + this.markPrevious(); + this.render(); + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event); + return; + case Event.KEY_DOWN: + this.markNext(); + this.render(); + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event); + return; + } + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return; + + this.changed = true; + this.hasFocus = true; + + if(this.observer) clearTimeout(this.observer); + this.observer = + setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); + }, + + activate: function() { + this.changed = false; + this.hasFocus = true; + this.getUpdatedChoices(); + }, + + onHover: function(event) { + var element = Event.findElement(event, 'LI'); + if(this.index != element.autocompleteIndex) + { + this.index = element.autocompleteIndex; + this.render(); + } + Event.stop(event); + }, + + onClick: function(event) { + var element = Event.findElement(event, 'LI'); + this.index = element.autocompleteIndex; + this.selectEntry(); + this.hide(); + }, + + onBlur: function(event) { + // needed to make click events working + setTimeout(this.hide.bind(this), 250); + this.hasFocus = false; + this.active = false; + }, + + render: function() { + if(this.entryCount > 0) { + for (var i = 0; i < this.entryCount; i++) + this.index==i ? + Element.addClassName(this.getEntry(i),"selected") : + Element.removeClassName(this.getEntry(i),"selected"); + + if(this.hasFocus) { + this.show(); + this.active = true; + } + } else { + this.active = false; + this.hide(); + } + }, + + markPrevious: function() { + if(this.index > 0) this.index-- + else this.index = this.entryCount-1; + this.getEntry(this.index).scrollIntoView(true); + }, + + markNext: function() { + if(this.index < this.entryCount-1) this.index++ + else this.index = 0; + this.getEntry(this.index).scrollIntoView(false); + }, + + getEntry: function(index) { + return this.update.firstChild.childNodes[index]; + }, + + getCurrentEntry: function() { + return this.getEntry(this.index); + }, + + selectEntry: function() { + this.active = false; + this.updateElement(this.getCurrentEntry()); + }, + + updateElement: function(selectedElement) { + if (this.options.updateElement) { + this.options.updateElement(selectedElement); + return; + } + var value = ''; + if (this.options.select) { + var nodes = document.getElementsByClassName(this.options.select, selectedElement) || []; + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); + } else + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); + + var lastTokenPos = this.findLastToken(); + if (lastTokenPos != -1) { + var newValue = this.element.value.substr(0, lastTokenPos + 1); + var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/); + if (whitespace) + newValue += whitespace[0]; + this.element.value = newValue + value; + } else { + this.element.value = value; + } + this.element.focus(); + + if (this.options.afterUpdateElement) + this.options.afterUpdateElement(this.element, selectedElement); + }, + + updateChoices: function(choices) { + if(!this.changed && this.hasFocus) { + this.update.innerHTML = choices; + Element.cleanWhitespace(this.update); + Element.cleanWhitespace(this.update.down()); + + if(this.update.firstChild && this.update.down().childNodes) { + this.entryCount = + this.update.down().childNodes.length; + for (var i = 0; i < this.entryCount; i++) { + var entry = this.getEntry(i); + entry.autocompleteIndex = i; + this.addObservers(entry); + } + } else { + this.entryCount = 0; + } + + this.stopIndicator(); + this.index = 0; + + if(this.entryCount==1 && this.options.autoSelect) { + this.selectEntry(); + this.hide(); + } else { + this.render(); + } + } + }, + + addObservers: function(element) { + Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); + Event.observe(element, "click", this.onClick.bindAsEventListener(this)); + }, + + onObserverEvent: function() { + this.changed = false; + if(this.getToken().length>=this.options.minChars) { + this.startIndicator(); + this.getUpdatedChoices(); + } else { + this.active = false; + this.hide(); + } + }, + + getToken: function() { + var tokenPos = this.findLastToken(); + if (tokenPos != -1) + var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,''); + else + var ret = this.element.value; + + return /\n/.test(ret) ? '' : ret; + }, + + findLastToken: function() { + var lastTokenPos = -1; + + for (var i=0; i<this.options.tokens.length; i++) { + var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]); + if (thisTokenPos > lastTokenPos) + lastTokenPos = thisTokenPos; + } + return lastTokenPos; + } +} + +Ajax.Autocompleter = Class.create(); +Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), { + initialize: function(element, update, url, options) { + this.baseInitialize(element, update, options); + this.options.asynchronous = true; + this.options.onComplete = this.onComplete.bind(this); + this.options.defaultParams = this.options.parameters || null; + this.url = url; + }, + + getUpdatedChoices: function() { + entry = encodeURIComponent(this.options.paramName) + '=' + + encodeURIComponent(this.getToken()); + + this.options.parameters = this.options.callback ? + this.options.callback(this.element, entry) : entry; + + if(this.options.defaultParams) + this.options.parameters += '&' + this.options.defaultParams; + + new Ajax.Request(this.url, this.options); + }, + + onComplete: function(request) { + this.updateChoices(request.responseText); + } + +}); + +// The local array autocompleter. Used when you'd prefer to +// inject an array of autocompletion options into the page, rather +// than sending out Ajax queries, which can be quite slow sometimes. +// +// The constructor takes four parameters. The first two are, as usual, +// the id of the monitored textbox, and id of the autocompletion menu. +// The third is the array you want to autocomplete from, and the fourth +// is the options block. +// +// Extra local autocompletion options: +// - choices - How many autocompletion choices to offer +// +// - partialSearch - If false, the autocompleter will match entered +// text only at the beginning of strings in the +// autocomplete array. Defaults to true, which will +// match text at the beginning of any *word* in the +// strings in the autocomplete array. If you want to +// search anywhere in the string, additionally set +// the option fullSearch to true (default: off). +// +// - fullSsearch - Search anywhere in autocomplete array strings. +// +// - partialChars - How many characters to enter before triggering +// a partial match (unlike minChars, which defines +// how many characters are required to do any match +// at all). Defaults to 2. +// +// - ignoreCase - Whether to ignore case when autocompleting. +// Defaults to true. +// +// It's possible to pass in a custom function as the 'selector' +// option, if you prefer to write your own autocompletion logic. +// In that case, the other options above will not apply unless +// you support them. + +Autocompleter.Local = Class.create(); +Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), { + initialize: function(element, update, array, options) { + this.baseInitialize(element, update, options); + this.options.array = array; + }, + + getUpdatedChoices: function() { + this.updateChoices(this.options.selector(this)); + }, + + setOptions: function(options) { + this.options = Object.extend({ + choices: 10, + partialSearch: true, + partialChars: 2, + ignoreCase: true, + fullSearch: false, + selector: function(instance) { + var ret = []; // Beginning matches + var partial = []; // Inside matches + var entry = instance.getToken(); + var count = 0; + + for (var i = 0; i < instance.options.array.length && + ret.length < instance.options.choices ; i++) { + + var elem = instance.options.array[i]; + var foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase()) : + elem.indexOf(entry); + + while (foundPos != -1) { + if (foundPos == 0 && elem.length != entry.length) { + ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + + elem.substr(entry.length) + "</li>"); + break; + } else if (entry.length >= instance.options.partialChars && + instance.options.partialSearch && foundPos != -1) { + if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { + partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" + + elem.substr(foundPos, entry.length) + "</strong>" + elem.substr( + foundPos + entry.length) + "</li>"); + break; + } + } + + foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : + elem.indexOf(entry, foundPos + 1); + + } + } + if (partial.length) + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)) + return "<ul>" + ret.join('') + "</ul>"; + } + }, options || {}); + } +}); + +// AJAX in-place editor +// +// see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor + +// Use this if you notice weird scrolling problems on some browsers, +// the DOM might be a bit confused when this gets called so do this +// waits 1 ms (with setTimeout) until it does the activation +Field.scrollFreeActivate = function(field) { + setTimeout(function() { + Field.activate(field); + }, 1); +} + +Ajax.InPlaceEditor = Class.create(); +Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99"; +Ajax.InPlaceEditor.prototype = { + initialize: function(element, url, options) { + this.url = url; + this.element = $(element); + + this.options = Object.extend({ + paramName: "value", + okButton: true, + okText: "ok", + cancelLink: true, + cancelText: "cancel", + savingText: "Saving...", + clickToEditText: "Click to edit", + okText: "ok", + rows: 1, + onComplete: function(transport, element) { + new Effect.Highlight(element, {startcolor: this.options.highlightcolor}); + }, + onFailure: function(transport) { + alert("Error communicating with the server: " + transport.responseText.stripTags()); + }, + callback: function(form) { + return Form.serialize(form); + }, + handleLineBreaks: true, + loadingText: 'Loading...', + savingClassName: 'inplaceeditor-saving', + loadingClassName: 'inplaceeditor-loading', + formClassName: 'inplaceeditor-form', + highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor, + highlightendcolor: "#FFFFFF", + externalControl: null, + submitOnBlur: false, + ajaxOptions: {}, + evalScripts: false + }, options || {}); + + if(!this.options.formId && this.element.id) { + this.options.formId = this.element.id + "-inplaceeditor"; + if ($(this.options.formId)) { + // there's already a form with that name, don't specify an id + this.options.formId = null; + } + } + + if (this.options.externalControl) { + this.options.externalControl = $(this.options.externalControl); + } + + this.originalBackground = Element.getStyle(this.element, 'background-color'); + if (!this.originalBackground) { + this.originalBackground = "transparent"; + } + + this.element.title = this.options.clickToEditText; + + this.onclickListener = this.enterEditMode.bindAsEventListener(this); + this.mouseoverListener = this.enterHover.bindAsEventListener(this); + this.mouseoutListener = this.leaveHover.bindAsEventListener(this); + Event.observe(this.element, 'click', this.onclickListener); + Event.observe(this.element, 'mouseover', this.mouseoverListener); + Event.observe(this.element, 'mouseout', this.mouseoutListener); + if (this.options.externalControl) { + Event.observe(this.options.externalControl, 'click', this.onclickListener); + Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener); + Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener); + } + }, + enterEditMode: function(evt) { + if (this.saving) return; + if (this.editing) return; + this.editing = true; + this.onEnterEditMode(); + if (this.options.externalControl) { + Element.hide(this.options.externalControl); + } + Element.hide(this.element); + this.createForm(); + this.element.parentNode.insertBefore(this.form, this.element); + if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField); + // stop the event to avoid a page refresh in Safari + if (evt) { + Event.stop(evt); + } + return false; + }, + createForm: function() { + this.form = document.createElement("form"); + this.form.id = this.options.formId; + Element.addClassName(this.form, this.options.formClassName) + this.form.onsubmit = this.onSubmit.bind(this); + + this.createEditField(); + + if (this.options.textarea) { + var br = document.createElement("br"); + this.form.appendChild(br); + } + + if (this.options.okButton) { + okButton = document.createElement("input"); + okButton.type = "submit"; + okButton.value = this.options.okText; + okButton.className = 'editor_ok_button'; + this.form.appendChild(okButton); + } + + if (this.options.cancelLink) { + cancelLink = document.createElement("a"); + cancelLink.href = "#"; + cancelLink.appendChild(document.createTextNode(this.options.cancelText)); + cancelLink.onclick = this.onclickCancel.bind(this); + cancelLink.className = 'editor_cancel'; + this.form.appendChild(cancelLink); + } + }, + hasHTMLLineBreaks: function(string) { + if (!this.options.handleLineBreaks) return false; + return string.match(/<br/i) || string.match(/<p>/i); + }, + convertHTMLLineBreaks: function(string) { + return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, ""); + }, + createEditField: function() { + var text; + if(this.options.loadTextURL) { + text = this.options.loadingText; + } else { + text = this.getText(); + } + + var obj = this; + + if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) { + this.options.textarea = false; + var textField = document.createElement("input"); + textField.obj = this; + textField.type = "text"; + textField.name = this.options.paramName; + textField.value = text; + textField.style.backgroundColor = this.options.highlightcolor; + textField.className = 'editor_field'; + var size = this.options.size || this.options.cols || 0; + if (size != 0) textField.size = size; + if (this.options.submitOnBlur) + textField.onblur = this.onSubmit.bind(this); + this.editField = textField; + } else { + this.options.textarea = true; + var textArea = document.createElement("textarea"); + textArea.obj = this; + textArea.name = this.options.paramName; + textArea.value = this.convertHTMLLineBreaks(text); + textArea.rows = this.options.rows; + textArea.cols = this.options.cols || 40; + textArea.className = 'editor_field'; + if (this.options.submitOnBlur) + textArea.onblur = this.onSubmit.bind(this); + this.editField = textArea; + } + + if(this.options.loadTextURL) { + this.loadExternalText(); + } + this.form.appendChild(this.editField); + }, + getText: function() { + return this.element.innerHTML; + }, + loadExternalText: function() { + Element.addClassName(this.form, this.options.loadingClassName); + this.editField.disabled = true; + new Ajax.Request( + this.options.loadTextURL, + Object.extend({ + asynchronous: true, + onComplete: this.onLoadedExternalText.bind(this) + }, this.options.ajaxOptions) + ); + }, + onLoadedExternalText: function(transport) { + Element.removeClassName(this.form, this.options.loadingClassName); + this.editField.disabled = false; + this.editField.value = transport.responseText.stripTags(); + Field.scrollFreeActivate(this.editField); + }, + onclickCancel: function() { + this.onComplete(); + this.leaveEditMode(); + return false; + }, + onFailure: function(transport) { + this.options.onFailure(transport); + if (this.oldInnerHTML) { + this.element.innerHTML = this.oldInnerHTML; + this.oldInnerHTML = null; + } + return false; + }, + onSubmit: function() { + // onLoading resets these so we need to save them away for the Ajax call + var form = this.form; + var value = this.editField.value; + + // do this first, sometimes the ajax call returns before we get a chance to switch on Saving... + // which means this will actually switch on Saving... *after* we've left edit mode causing Saving... + // to be displayed indefinitely + this.onLoading(); + + if (this.options.evalScripts) { + new Ajax.Request( + this.url, Object.extend({ + parameters: this.options.callback(form, value), + onComplete: this.onComplete.bind(this), + onFailure: this.onFailure.bind(this), + asynchronous:true, + evalScripts:true + }, this.options.ajaxOptions)); + } else { + new Ajax.Updater( + { success: this.element, + // don't update on failure (this could be an option) + failure: null }, + this.url, Object.extend({ + parameters: this.options.callback(form, value), + onComplete: this.onComplete.bind(this), + onFailure: this.onFailure.bind(this) + }, this.options.ajaxOptions)); + } + // stop the event to avoid a page refresh in Safari + if (arguments.length > 1) { + Event.stop(arguments[0]); + } + return false; + }, + onLoading: function() { + this.saving = true; + this.removeForm(); + this.leaveHover(); + this.showSaving(); + }, + showSaving: function() { + this.oldInnerHTML = this.element.innerHTML; + this.element.innerHTML = this.options.savingText; + Element.addClassName(this.element, this.options.savingClassName); + this.element.style.backgroundColor = this.originalBackground; + Element.show(this.element); + }, + removeForm: function() { + if(this.form) { + if (this.form.parentNode) Element.remove(this.form); + this.form = null; + } + }, + enterHover: function() { + if (this.saving) return; + this.element.style.backgroundColor = this.options.highlightcolor; + if (this.effect) { + this.effect.cancel(); + } + Element.addClassName(this.element, this.options.hoverClassName) + }, + leaveHover: function() { + if (this.options.backgroundColor) { + this.element.style.backgroundColor = this.oldBackground; + } + Element.removeClassName(this.element, this.options.hoverClassName) + if (this.saving) return; + this.effect = new Effect.Highlight(this.element, { + startcolor: this.options.highlightcolor, + endcolor: this.options.highlightendcolor, + restorecolor: this.originalBackground + }); + }, + leaveEditMode: function() { + Element.removeClassName(this.element, this.options.savingClassName); + this.removeForm(); + this.leaveHover(); + this.element.style.backgroundColor = this.originalBackground; + Element.show(this.element); + if (this.options.externalControl) { + Element.show(this.options.externalControl); + } + this.editing = false; + this.saving = false; + this.oldInnerHTML = null; + this.onLeaveEditMode(); + }, + onComplete: function(transport) { + this.leaveEditMode(); + this.options.onComplete.bind(this)(transport, this.element); + }, + onEnterEditMode: function() {}, + onLeaveEditMode: function() {}, + dispose: function() { + if (this.oldInnerHTML) { + this.element.innerHTML = this.oldInnerHTML; + } + this.leaveEditMode(); + Event.stopObserving(this.element, 'click', this.onclickListener); + Event.stopObserving(this.element, 'mouseover', this.mouseoverListener); + Event.stopObserving(this.element, 'mouseout', this.mouseoutListener); + if (this.options.externalControl) { + Event.stopObserving(this.options.externalControl, 'click', this.onclickListener); + Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener); + Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener); + } + } +}; + +Ajax.InPlaceCollectionEditor = Class.create(); +Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype); +Object.extend(Ajax.InPlaceCollectionEditor.prototype, { + createEditField: function() { + if (!this.cached_selectTag) { + var selectTag = document.createElement("select"); + var collection = this.options.collection || []; + var optionTag; + collection.each(function(e,i) { + optionTag = document.createElement("option"); + optionTag.value = (e instanceof Array) ? e[0] : e; + if((typeof this.options.value == 'undefined') && + ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true; + if(this.options.value==optionTag.value) optionTag.selected = true; + optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e)); + selectTag.appendChild(optionTag); + }.bind(this)); + this.cached_selectTag = selectTag; + } + + this.editField = this.cached_selectTag; + if(this.options.loadTextURL) this.loadExternalText(); + this.form.appendChild(this.editField); + this.options.callback = function(form, value) { + return "value=" + encodeURIComponent(value); + } + } +}); + +// Delayed observer, like Form.Element.Observer, +// but waits for delay after last key input +// Ideal for live-search fields + +Form.Element.DelayedObserver = Class.create(); +Form.Element.DelayedObserver.prototype = { + initialize: function(element, delay, callback) { + this.delay = delay || 0.5; + this.element = $(element); + this.callback = callback; + this.timer = null; + this.lastValue = $F(this.element); + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); + }, + delayedListener: function(event) { + if(this.lastValue == $F(this.element)) return; + if(this.timer) clearTimeout(this.timer); + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); + this.lastValue = $F(this.element); + }, + onTimerEvent: function() { + this.timer = null; + this.callback(this.element, $F(this.element)); + } +}; diff --git a/public/javascripts/dragdrop.js b/public/javascripts/dragdrop.js new file mode 100644 index 0000000..c71ddb8 --- /dev/null +++ b/public/javascripts/dragdrop.js @@ -0,0 +1,942 @@ +// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, [email protected]) +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +if(typeof Effect == 'undefined') + throw("dragdrop.js requires including script.aculo.us' effects.js library"); + +var Droppables = { + drops: [], + + remove: function(element) { + this.drops = this.drops.reject(function(d) { return d.element==$(element) }); + }, + + add: function(element) { + element = $(element); + var options = Object.extend({ + greedy: true, + hoverclass: null, + tree: false + }, arguments[1] || {}); + + // cache containers + if(options.containment) { + options._containers = []; + var containment = options.containment; + if((typeof containment == 'object') && + (containment.constructor == Array)) { + containment.each( function(c) { options._containers.push($(c)) }); + } else { + options._containers.push($(containment)); + } + } + + if(options.accept) options.accept = [options.accept].flatten(); + + Element.makePositioned(element); // fix IE + options.element = element; + + this.drops.push(options); + }, + + findDeepestChild: function(drops) { + deepest = drops[0]; + + for (i = 1; i < drops.length; ++i) + if (Element.isParent(drops[i].element, deepest.element)) + deepest = drops[i]; + + return deepest; + }, + + isContained: function(element, drop) { + var containmentNode; + if(drop.tree) { + containmentNode = element.treeNode; + } else { + containmentNode = element.parentNode; + } + return drop._containers.detect(function(c) { return containmentNode == c }); + }, + + isAffected: function(point, element, drop) { + return ( + (drop.element!=element) && + ((!drop._containers) || + this.isContained(element, drop)) && + ((!drop.accept) || + (Element.classNames(element).detect( + function(v) { return drop.accept.include(v) } ) )) && + Position.within(drop.element, point[0], point[1]) ); + }, + + deactivate: function(drop) { + if(drop.hoverclass) + Element.removeClassName(drop.element, drop.hoverclass); + this.last_active = null; + }, + + activate: function(drop) { + if(drop.hoverclass) + Element.addClassName(drop.element, drop.hoverclass); + this.last_active = drop; + }, + + show: function(point, element) { + if(!this.drops.length) return; + var affected = []; + + if(this.last_active) this.deactivate(this.last_active); + this.drops.each( function(drop) { + if(Droppables.isAffected(point, element, drop)) + affected.push(drop); + }); + + if(affected.length>0) { + drop = Droppables.findDeepestChild(affected); + Position.within(drop.element, point[0], point[1]); + if(drop.onHover) + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); + + Droppables.activate(drop); + } + }, + + fire: function(event, element) { + if(!this.last_active) return; + Position.prepare(); + + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) + if (this.last_active.onDrop) + this.last_active.onDrop(element, this.last_active.element, event); + }, + + reset: function() { + if(this.last_active) + this.deactivate(this.last_active); + } +} + +var Draggables = { + drags: [], + observers: [], + + register: function(draggable) { + if(this.drags.length == 0) { + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.updateDrag.bindAsEventListener(this); + this.eventKeypress = this.keyPress.bindAsEventListener(this); + + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + Event.observe(document, "keypress", this.eventKeypress); + } + this.drags.push(draggable); + }, + + unregister: function(draggable) { + this.drags = this.drags.reject(function(d) { return d==draggable }); + if(this.drags.length == 0) { + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + Event.stopObserving(document, "keypress", this.eventKeypress); + } + }, + + activate: function(draggable) { + if(draggable.options.delay) { + this._timeout = setTimeout(function() { + Draggables._timeout = null; + window.focus(); + Draggables.activeDraggable = draggable; + }.bind(this), draggable.options.delay); + } else { + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari + this.activeDraggable = draggable; + } + }, + + deactivate: function() { + this.activeDraggable = null; + }, + + updateDrag: function(event) { + if(!this.activeDraggable) return; + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + // Mozilla-based browsers fire successive mousemove events with + // the same coordinates, prevent needless redrawing (moz bug?) + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; + this._lastPointer = pointer; + + this.activeDraggable.updateDrag(event, pointer); + }, + + endDrag: function(event) { + if(this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + } + if(!this.activeDraggable) return; + this._lastPointer = null; + this.activeDraggable.endDrag(event); + this.activeDraggable = null; + }, + + keyPress: function(event) { + if(this.activeDraggable) + this.activeDraggable.keyPress(event); + }, + + addObserver: function(observer) { + this.observers.push(observer); + this._cacheObserverCallbacks(); + }, + + removeObserver: function(element) { // element instead of observer fixes mem leaks + this.observers = this.observers.reject( function(o) { return o.element==element }); + this._cacheObserverCallbacks(); + }, + + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' + if(this[eventName+'Count'] > 0) + this.observers.each( function(o) { + if(o[eventName]) o[eventName](eventName, draggable, event); + }); + if(draggable.options[eventName]) draggable.options[eventName](draggable, event); + }, + + _cacheObserverCallbacks: function() { + ['onStart','onEnd','onDrag'].each( function(eventName) { + Draggables[eventName+'Count'] = Draggables.observers.select( + function(o) { return o[eventName]; } + ).length; + }); + } +} + +/*--------------------------------------------------------------------------*/ + +var Draggable = Class.create(); +Draggable._dragging = {}; + +Draggable.prototype = { + initialize: function(element) { + var defaults = { + handle: false, + reverteffect: function(element, top_offset, left_offset) { + var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; + new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, + queue: {scope:'_draggable', position:'end'} + }); + }, + endeffect: function(element) { + var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0; + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, + queue: {scope:'_draggable', position:'end'}, + afterFinish: function(){ + Draggable._dragging[element] = false + } + }); + }, + zindex: 1000, + revert: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } + delay: 0 + }; + + if(!arguments[1] || typeof arguments[1].endeffect == 'undefined') + Object.extend(defaults, { + starteffect: function(element) { + element._opacity = Element.getOpacity(element); + Draggable._dragging[element] = true; + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + } + }); + + var options = Object.extend(defaults, arguments[1] || {}); + + this.element = $(element); + + if(options.handle && (typeof options.handle == 'string')) + this.handle = this.element.down('.'+options.handle, 0); + + if(!this.handle) this.handle = $(options.handle); + if(!this.handle) this.handle = this.element; + + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { + options.scroll = $(options.scroll); + this._isScrollChild = Element.childOf(this.element, options.scroll); + } + + Element.makePositioned(this.element); // fix IE + + this.delta = this.currentDelta(); + this.options = options; + this.dragging = false; + + this.eventMouseDown = this.initDrag.bindAsEventListener(this); + Event.observe(this.handle, "mousedown", this.eventMouseDown); + + Draggables.register(this); + }, + + destroy: function() { + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); + Draggables.unregister(this); + }, + + currentDelta: function() { + return([ + parseInt(Element.getStyle(this.element,'left') || '0'), + parseInt(Element.getStyle(this.element,'top') || '0')]); + }, + + initDrag: function(event) { + if(typeof Draggable._dragging[this.element] != 'undefined' && + Draggable._dragging[this.element]) return; + if(Event.isLeftClick(event)) { + // abort on form elements, fixes a Firefox issue + var src = Event.element(event); + if(src.tagName && ( + src.tagName=='INPUT' || + src.tagName=='SELECT' || + src.tagName=='OPTION' || + src.tagName=='BUTTON' || + src.tagName=='TEXTAREA')) return; + + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var pos = Position.cumulativeOffset(this.element); + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); + + Draggables.activate(this); + Event.stop(event); + } + }, + + startDrag: function(event) { + this.dragging = true; + + if(this.options.zindex) { + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); + this.element.style.zIndex = this.options.zindex; + } + + if(this.options.ghosting) { + this._clone = this.element.cloneNode(true); + Position.absolutize(this.element); + this.element.parentNode.insertBefore(this._clone, this.element); + } + + if(this.options.scroll) { + if (this.options.scroll == window) { + var where = this._getWindowScroll(this.options.scroll); + this.originalScrollLeft = where.left; + this.originalScrollTop = where.top; + } else { + this.originalScrollLeft = this.options.scroll.scrollLeft; + this.originalScrollTop = this.options.scroll.scrollTop; + } + } + + Draggables.notify('onStart', this, event); + + if(this.options.starteffect) this.options.starteffect(this.element); + }, + + updateDrag: function(event, pointer) { + if(!this.dragging) this.startDrag(event); + Position.prepare(); + Droppables.show(pointer, this.element); + Draggables.notify('onDrag', this, event); + + this.draw(pointer); + if(this.options.change) this.options.change(this); + + if(this.options.scroll) { + this.stopScrolling(); + + var p; + if (this.options.scroll == window) { + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } + } else { + p = Position.page(this.options.scroll); + p[0] += this.options.scroll.scrollLeft + Position.deltaX; + p[1] += this.options.scroll.scrollTop + Position.deltaY; + p.push(p[0]+this.options.scroll.offsetWidth); + p.push(p[1]+this.options.scroll.offsetHeight); + } + var speed = [0,0]; + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); + this.startScrolling(speed); + } + + // fix AppleWebKit rendering + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); + + Event.stop(event); + }, + + finishDrag: function(event, success) { + this.dragging = false; + + if(this.options.ghosting) { + Position.relativize(this.element); + Element.remove(this._clone); + this._clone = null; + } + + if(success) Droppables.fire(event, this.element); + Draggables.notify('onEnd', this, event); + + var revert = this.options.revert; + if(revert && typeof revert == 'function') revert = revert(this.element); + + var d = this.currentDelta(); + if(revert && this.options.reverteffect) { + this.options.reverteffect(this.element, + d[1]-this.delta[1], d[0]-this.delta[0]); + } else { + this.delta = d; + } + + if(this.options.zindex) + this.element.style.zIndex = this.originalZ; + + if(this.options.endeffect) + this.options.endeffect(this.element); + + Draggables.deactivate(this); + Droppables.reset(); + }, + + keyPress: function(event) { + if(event.keyCode!=Event.KEY_ESC) return; + this.finishDrag(event, false); + Event.stop(event); + }, + + endDrag: function(event) { + if(!this.dragging) return; + this.stopScrolling(); + this.finishDrag(event, true); + Event.stop(event); + }, + + draw: function(point) { + var pos = Position.cumulativeOffset(this.element); + if(this.options.ghosting) { + var r = Position.realOffset(this.element); + pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; + } + + var d = this.currentDelta(); + pos[0] -= d[0]; pos[1] -= d[1]; + + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; + } + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]) + }.bind(this)); + + if(this.options.snap) { + if(typeof this.options.snap == 'function') { + p = this.options.snap(p[0],p[1],this); + } else { + if(this.options.snap instanceof Array) { + p = p.map( function(v, i) { + return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this)) + } else { + p = p.map( function(v) { + return Math.round(v/this.options.snap)*this.options.snap }.bind(this)) + } + }} + + var style = this.element.style; + if((!this.options.constraint) || (this.options.constraint=='horizontal')) + style.left = p[0] + "px"; + if((!this.options.constraint) || (this.options.constraint=='vertical')) + style.top = p[1] + "px"; + + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering + }, + + stopScrolling: function() { + if(this.scrollInterval) { + clearInterval(this.scrollInterval); + this.scrollInterval = null; + Draggables._lastScrollPointer = null; + } + }, + + startScrolling: function(speed) { + if(!(speed[0] || speed[1])) return; + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; + this.lastScrolled = new Date(); + this.scrollInterval = setInterval(this.scroll.bind(this), 10); + }, + + scroll: function() { + var current = new Date(); + var delta = current - this.lastScrolled; + this.lastScrolled = current; + if(this.options.scroll == window) { + with (this._getWindowScroll(this.options.scroll)) { + if (this.scrollSpeed[0] || this.scrollSpeed[1]) { + var d = delta / 1000; + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); + } + } + } else { + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; + } + + Position.prepare(); + Droppables.show(Draggables._lastPointer, this.element); + Draggables.notify('onDrag', this); + if (this._isScrollChild) { + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; + if (Draggables._lastScrollPointer[0] < 0) + Draggables._lastScrollPointer[0] = 0; + if (Draggables._lastScrollPointer[1] < 0) + Draggables._lastScrollPointer[1] = 0; + this.draw(Draggables._lastScrollPointer); + } + + if(this.options.change) this.options.change(this); + }, + + _getWindowScroll: function(w) { + var T, L, W, H; + with (w.document) { + if (w.document.documentElement && documentElement.scrollTop) { + T = documentElement.scrollTop; + L = documentElement.scrollLeft; + } else if (w.document.body) { + T = body.scrollTop; + L = body.scrollLeft; + } + if (w.innerWidth) { + W = w.innerWidth; + H = w.innerHeight; + } else if (w.document.documentElement && documentElement.clientWidth) { + W = documentElement.clientWidth; + H = documentElement.clientHeight; + } else { + W = body.offsetWidth; + H = body.offsetHeight + } + } + return { top: T, left: L, width: W, height: H }; + } +} + +/*--------------------------------------------------------------------------*/ + +var SortableObserver = Class.create(); +SortableObserver.prototype = { + initialize: function(element, observer) { + this.element = $(element); + this.observer = observer; + this.lastValue = Sortable.serialize(this.element); + }, + + onStart: function() { + this.lastValue = Sortable.serialize(this.element); + }, + + onEnd: function() { + Sortable.unmark(); + if(this.lastValue != Sortable.serialize(this.element)) + this.observer(this.element) + } +} + +var Sortable = { + SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, + + sortables: {}, + + _findRootElement: function(element) { + while (element.tagName != "BODY") { + if(element.id && Sortable.sortables[element.id]) return element; + element = element.parentNode; + } + }, + + options: function(element) { + element = Sortable._findRootElement($(element)); + if(!element) return; + return Sortable.sortables[element.id]; + }, + + destroy: function(element){ + var s = Sortable.options(element); + + if(s) { + Draggables.removeObserver(s.element); + s.droppables.each(function(d){ Droppables.remove(d) }); + s.draggables.invoke('destroy'); + + delete Sortable.sortables[s.element.id]; + } + }, + + create: function(element) { + element = $(element); + var options = Object.extend({ + element: element, + tag: 'li', // assumes li children, override with tag: 'tagname' + dropOnEmpty: false, + tree: false, + treeTag: 'ul', + overlap: 'vertical', // one of 'vertical', 'horizontal' + constraint: 'vertical', // one of 'vertical', 'horizontal', false + containment: element, // also takes array of elements (or id's); or false + handle: false, // or a CSS class + only: false, + delay: 0, + hoverclass: null, + ghosting: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + format: this.SERIALIZE_RULE, + onChange: Prototype.emptyFunction, + onUpdate: Prototype.emptyFunction + }, arguments[1] || {}); + + // clear any old sortable with same element + this.destroy(element); + + // build options for the draggables + var options_for_draggable = { + revert: true, + scroll: options.scroll, + scrollSpeed: options.scrollSpeed, + scrollSensitivity: options.scrollSensitivity, + delay: options.delay, + ghosting: options.ghosting, + constraint: options.constraint, + handle: options.handle }; + + if(options.starteffect) + options_for_draggable.starteffect = options.starteffect; + + if(options.reverteffect) + options_for_draggable.reverteffect = options.reverteffect; + else + if(options.ghosting) options_for_draggable.reverteffect = function(element) { + element.style.top = 0; + element.style.left = 0; + }; + + if(options.endeffect) + options_for_draggable.endeffect = options.endeffect; + + if(options.zindex) + options_for_draggable.zindex = options.zindex; + + // build options for the droppables + var options_for_droppable = { + overlap: options.overlap, + containment: options.containment, + tree: options.tree, + hoverclass: options.hoverclass, + onHover: Sortable.onHover + } + + var options_for_tree = { + onHover: Sortable.onEmptyHover, + overlap: options.overlap, + containment: options.containment, + hoverclass: options.hoverclass + } + + // fix for gecko engine + Element.cleanWhitespace(element); + + options.draggables = []; + options.droppables = []; + + // drop on empty handling + if(options.dropOnEmpty || options.tree) { + Droppables.add(element, options_for_tree); + options.droppables.push(element); + } + + (this.findElements(element, options) || []).each( function(e) { + // handles are per-draggable + var handle = options.handle ? + $(e).down('.'+options.handle,0) : e; + options.draggables.push( + new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); + Droppables.add(e, options_for_droppable); + if(options.tree) e.treeNode = element; + options.droppables.push(e); + }); + + if(options.tree) { + (Sortable.findTreeElements(element, options) || []).each( function(e) { + Droppables.add(e, options_for_tree); + e.treeNode = element; + options.droppables.push(e); + }); + } + + // keep reference + this.sortables[element.id] = options; + + // for onupdate + Draggables.addObserver(new SortableObserver(element, options.onUpdate)); + + }, + + // return all suitable-for-sortable elements in a guaranteed order + findElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.tag); + }, + + findTreeElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.treeTag); + }, + + onHover: function(element, dropon, overlap) { + if(Element.isParent(dropon, element)) return; + + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { + return; + } else if(overlap>0.5) { + Sortable.mark(dropon, 'before'); + if(dropon.previousSibling != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, dropon); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } else { + Sortable.mark(dropon, 'after'); + var nextElement = dropon.nextSibling || null; + if(nextElement != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, nextElement); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } + }, + + onEmptyHover: function(element, dropon, overlap) { + var oldParentNode = element.parentNode; + var droponOptions = Sortable.options(dropon); + + if(!Element.isParent(dropon, element)) { + var index; + + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); + var child = null; + + if(children) { + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); + + for (index = 0; index < children.length; index += 1) { + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { + offset -= Element.offsetSize (children[index], droponOptions.overlap); + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { + child = index + 1 < children.length ? children[index + 1] : null; + break; + } else { + child = children[index]; + break; + } + } + } + + dropon.insertBefore(element, child); + + Sortable.options(oldParentNode).onChange(element); + droponOptions.onChange(element); + } + }, + + unmark: function() { + if(Sortable._marker) Sortable._marker.hide(); + }, + + mark: function(dropon, position) { + // mark on ghosting only + var sortable = Sortable.options(dropon.parentNode); + if(sortable && !sortable.ghosting) return; + + if(!Sortable._marker) { + Sortable._marker = + ($('dropmarker') || Element.extend(document.createElement('DIV'))). + hide().addClassName('dropmarker').setStyle({position:'absolute'}); + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); + } + var offsets = Position.cumulativeOffset(dropon); + Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); + + if(position=='after') + if(sortable.overlap == 'horizontal') + Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); + else + Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); + + Sortable._marker.show(); + }, + + _tree: function(element, options, parent) { + var children = Sortable.findElements(element, options) || []; + + for (var i = 0; i < children.length; ++i) { + var match = children[i].id.match(options.format); + + if (!match) continue; + + var child = { + id: encodeURIComponent(match ? match[1] : null), + element: element, + parent: parent, + children: [], + position: parent.children.length, + container: $(children[i]).down(options.treeTag) + } + + /* Get the element containing the children and recurse over it */ + if (child.container) + this._tree(child.container, options, child) + + parent.children.push (child); + } + + return parent; + }, + + tree: function(element) { + element = $(element); + var sortableOptions = this.options(element); + var options = Object.extend({ + tag: sortableOptions.tag, + treeTag: sortableOptions.treeTag, + only: sortableOptions.only, + name: element.id, + format: sortableOptions.format + }, arguments[1] || {}); + + var root = { + id: null, + parent: null, + children: [], + container: element, + position: 0 + } + + return Sortable._tree(element, options, root); + }, + + /* Construct a [i] index for a particular node */ + _constructIndex: function(node) { + var index = ''; + do { + if (node.id) index = '[' + node.position + ']' + index; + } while ((node = node.parent) != null); + return index; + }, + + sequence: function(element) { + element = $(element); + var options = Object.extend(this.options(element), arguments[1] || {}); + + return $(this.findElements(element, options) || []).map( function(item) { + return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; + }); + }, + + setSequence: function(element, new_sequence) { + element = $(element); + var options = Object.extend(this.options(element), arguments[2] || {}); + + var nodeMap = {}; + this.findElements(element, options).each( function(n) { + if (n.id.match(options.format)) + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; + n.parentNode.removeChild(n); + }); + + new_sequence.each(function(ident) { + var n = nodeMap[ident]; + if (n) { + n[1].appendChild(n[0]); + delete nodeMap[ident]; + } + }); + }, + + serialize: function(element) { + element = $(element); + var options = Object.extend(Sortable.options(element), arguments[1] || {}); + var name = encodeURIComponent( + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); + + if (options.tree) { + return Sortable.tree(element, arguments[1]).children.map( function (item) { + return [name + Sortable._constructIndex(item) + "[id]=" + + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); + }).flatten().join('&'); + } else { + return Sortable.sequence(element, arguments[1]).map( function(item) { + return name + "[]=" + encodeURIComponent(item); + }).join('&'); + } + } +} + +// Returns true if child is contained within element +Element.isParent = function(child, element) { + if (!child.parentNode || child == element) return false; + if (child.parentNode == element) return true; + return Element.isParent(child.parentNode, element); +} + +Element.findChildren = function(element, only, recursive, tagName) { + if(!element.hasChildNodes()) return null; + tagName = tagName.toUpperCase(); + if(only) only = [only].flatten(); + var elements = []; + $A(element.childNodes).each( function(e) { + if(e.tagName && e.tagName.toUpperCase()==tagName && + (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) + elements.push(e); + if(recursive) { + var grandchildren = Element.findChildren(e, only, recursive, tagName); + if(grandchildren) elements.push(grandchildren); + } + }); + + return (elements.length>0 ? elements.flatten() : []); +} + +Element.offsetSize = function (element, type) { + return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; +} diff --git a/public/javascripts/effects.js b/public/javascripts/effects.js new file mode 100644 index 0000000..3b02eda --- /dev/null +++ b/public/javascripts/effects.js @@ -0,0 +1,1088 @@ +// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// Contributors: +// Justin Palmer (http://encytemedia.com/) +// Mark Pilgrim (http://diveintomark.org/) +// Martin Bialasinki +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { + var color = '#'; + if(this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); + } else { + if(this.slice(0,1) == '#') { + if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if(this.length==7) color = this.toLowerCase(); + } + } + return(color.length==7 ? color : (arguments[0] || this)); +} + +/*--------------------------------------------------------------------------*/ + +Element.collectTextNodes = function(element) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); + }).flatten().join(''); +} + +Element.collectTextNodesIgnoreClass = function(element, className) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + Element.collectTextNodesIgnoreClass(node, className) : '')); + }).flatten().join(''); +} + +Element.setContentZoom = function(element, percent) { + element = $(element); + element.setStyle({fontSize: (percent/100) + 'em'}); + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); + return element; +} + +Element.getOpacity = function(element){ + element = $(element); + var opacity; + if (opacity = element.getStyle('opacity')) + return parseFloat(opacity); + if (opacity = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if(opacity[1]) return parseFloat(opacity[1]) / 100; + return 1.0; +} + +Element.setOpacity = function(element, value){ + element= $(element); + if (value == 1){ + element.setStyle({ opacity: + (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? + 0.999999 : 1.0 }); + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.setStyle({filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')}); + } else { + if(value < 0.00001) value = 0; + element.setStyle({opacity: value}); + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.setStyle( + { filter: element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') + + 'alpha(opacity='+value*100+')' }); + } + return element; +} + +Element.getInlineOpacity = function(element){ + return $(element).style.opacity || ''; +} + +Element.forceRerendering = function(element) { + try { + element = $(element); + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch(e) { } +}; + +/*--------------------------------------------------------------------------*/ + +Array.prototype.call = function() { + var args = arguments; + this.each(function(f){ f.apply(this, args) }); +} + +/*--------------------------------------------------------------------------*/ + +var Effect = { + _elementDoesNotExistError: { + name: 'ElementDoesNotExistError', + message: 'The specified DOM element does not exist, but is required for this effect to operate' + }, + tagifyText: function(element) { + if(typeof Builder == 'undefined') + throw("Effect.tagifyText requires including script.aculo.us' builder.js library"); + + var tagifyStyle = 'position:relative'; + if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1'; + + element = $(element); + $A(element.childNodes).each( function(child) { + if(child.nodeType==3) { + child.nodeValue.toArray().each( function(character) { + element.insertBefore( + Builder.node('span',{style: tagifyStyle}, + character == ' ' ? String.fromCharCode(160) : character), + child); + }); + Element.remove(child); + } + }); + }, + multiple: function(element, effect) { + var elements; + if(((typeof element == 'object') || + (typeof element == 'function')) && + (element.length)) + elements = element; + else + elements = $(element).childNodes; + + var options = Object.extend({ + speed: 0.1, + delay: 0.0 + }, arguments[2] || {}); + var masterDelay = options.delay; + + $A(elements).each( function(element, index) { + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); + }); + }, + PAIRS: { + 'slide': ['SlideDown','SlideUp'], + 'blind': ['BlindDown','BlindUp'], + 'appear': ['Appear','Fade'] + }, + toggle: function(element, effect) { + element = $(element); + effect = (effect || 'appear').toLowerCase(); + var options = Object.extend({ + queue: { position:'end', scope:(element.id || 'global'), limit: 1 } + }, arguments[2] || {}); + Effect[element.visible() ? + Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); + } +}; + +var Effect2 = Effect; // deprecated + +/* ------------- transitions ------------- */ + +Effect.Transitions = { + linear: Prototype.K, + sinoidal: function(pos) { + return (-Math.cos(pos*Math.PI)/2) + 0.5; + }, + reverse: function(pos) { + return 1-pos; + }, + flicker: function(pos) { + return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; + }, + wobble: function(pos) { + return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; + }, + pulse: function(pos, pulses) { + pulses = pulses || 5; + return ( + Math.round((pos % (1/pulses)) * pulses) == 0 ? + ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) : + 1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) + ); + }, + none: function(pos) { + return 0; + }, + full: function(pos) { + return 1; + } +}; + +/* ------------- core effects ------------- */ + +Effect.ScopedQueue = Class.create(); +Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), { + initialize: function() { + this.effects = []; + this.interval = null; + }, + _each: function(iterator) { + this.effects._each(iterator); + }, + add: function(effect) { + var timestamp = new Date().getTime(); + + var position = (typeof effect.options.queue == 'string') ? + effect.options.queue : effect.options.queue.position; + + switch(position) { + case 'front': + // move unstarted effects after this effect + this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { + e.startOn += effect.finishOn; + e.finishOn += effect.finishOn; + }); + break; + case 'with-last': + timestamp = this.effects.pluck('startOn').max() || timestamp; + break; + case 'end': + // start effect after last queued effect has finished + timestamp = this.effects.pluck('finishOn').max() || timestamp; + break; + } + + effect.startOn += timestamp; + effect.finishOn += timestamp; + + if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + this.effects.push(effect); + + if(!this.interval) + this.interval = setInterval(this.loop.bind(this), 40); + }, + remove: function(effect) { + this.effects = this.effects.reject(function(e) { return e==effect }); + if(this.effects.length == 0) { + clearInterval(this.interval); + this.interval = null; + } + }, + loop: function() { + var timePos = new Date().getTime(); + this.effects.invoke('loop', timePos); + } +}); + +Effect.Queues = { + instances: $H(), + get: function(queueName) { + if(typeof queueName != 'string') return queueName; + + if(!this.instances[queueName]) + this.instances[queueName] = new Effect.ScopedQueue(); + + return this.instances[queueName]; + } +} +Effect.Queue = Effect.Queues.get('global'); + +Effect.DefaultOptions = { + transition: Effect.Transitions.sinoidal, + duration: 1.0, // seconds + fps: 25.0, // max. 25fps due to Effect.Queue implementation + sync: false, // true for combining + from: 0.0, + to: 1.0, + delay: 0.0, + queue: 'parallel' +} + +Effect.Base = function() {}; +Effect.Base.prototype = { + position: null, + start: function(options) { + this.options = Object.extend(Object.extend({},Effect.DefaultOptions), options || {}); + this.currentFrame = 0; + this.state = 'idle'; + this.startOn = this.options.delay*1000; + this.finishOn = this.startOn + (this.options.duration*1000); + this.event('beforeStart'); + if(!this.options.sync) + Effect.Queues.get(typeof this.options.queue == 'string' ? + 'global' : this.options.queue.scope).add(this); + }, + loop: function(timePos) { + if(timePos >= this.startOn) { + if(timePos >= this.finishOn) { + this.render(1.0); + this.cancel(); + this.event('beforeFinish'); + if(this.finish) this.finish(); + this.event('afterFinish'); + return; + } + var pos = (timePos - this.startOn) / (this.finishOn - this.startOn); + var frame = Math.round(pos * this.options.fps * this.options.duration); + if(frame > this.currentFrame) { + this.render(pos); + this.currentFrame = frame; + } + } + }, + render: function(pos) { + if(this.state == 'idle') { + this.state = 'running'; + this.event('beforeSetup'); + if(this.setup) this.setup(); + this.event('afterSetup'); + } + if(this.state == 'running') { + if(this.options.transition) pos = this.options.transition(pos); + pos *= (this.options.to-this.options.from); + pos += this.options.from; + this.position = pos; + this.event('beforeUpdate'); + if(this.update) this.update(pos); + this.event('afterUpdate'); + } + }, + cancel: function() { + if(!this.options.sync) + Effect.Queues.get(typeof this.options.queue == 'string' ? + 'global' : this.options.queue.scope).remove(this); + this.state = 'finished'; + }, + event: function(eventName) { + if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); + if(this.options[eventName]) this.options[eventName](this); + }, + inspect: function() { + return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>'; + } +} + +Effect.Parallel = Class.create(); +Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), { + initialize: function(effects) { + this.effects = effects || []; + this.start(arguments[1]); + }, + update: function(position) { + this.effects.invoke('render', position); + }, + finish: function(position) { + this.effects.each( function(effect) { + effect.render(1.0); + effect.cancel(); + effect.event('beforeFinish'); + if(effect.finish) effect.finish(position); + effect.event('afterFinish'); + }); + } +}); + +Effect.Event = Class.create(); +Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), { + initialize: function() { + var options = Object.extend({ + duration: 0 + }, arguments[0] || {}); + this.start(options); + }, + update: Prototype.emptyFunction +}); + +Effect.Opacity = Class.create(); +Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + // make this work on IE on elements without 'layout' + if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + var options = Object.extend({ + from: this.element.getOpacity() || 0.0, + to: 1.0 + }, arguments[1] || {}); + this.start(options); + }, + update: function(position) { + this.element.setOpacity(position); + } +}); + +Effect.Move = Class.create(); +Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + x: 0, + y: 0, + mode: 'relative' + }, arguments[1] || {}); + this.start(options); + }, + setup: function() { + // Bug in Opera: Opera returns the "real" position of a static element or + // relative element that does not have top/left explicitly set. + // ==> Always set top and left for position relative elements in your stylesheets + // (to 0 if you do not need them) + this.element.makePositioned(); + this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); + this.originalTop = parseFloat(this.element.getStyle('top') || '0'); + if(this.options.mode == 'absolute') { + // absolute movement, so we need to calc deltaX and deltaY + this.options.x = this.options.x - this.originalLeft; + this.options.y = this.options.y - this.originalTop; + } + }, + update: function(position) { + this.element.setStyle({ + left: Math.round(this.options.x * position + this.originalLeft) + 'px', + top: Math.round(this.options.y * position + this.originalTop) + 'px' + }); + } +}); + +// for backwards compatibility +Effect.MoveBy = function(element, toTop, toLeft) { + return new Effect.Move(element, + Object.extend({ x: toLeft, y: toTop }, arguments[3] || {})); +}; + +Effect.Scale = Class.create(); +Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), { + initialize: function(element, percent) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + scaleX: true, + scaleY: true, + scaleContent: true, + scaleFromCenter: false, + scaleMode: 'box', // 'box' or 'contents' or {} with provided values + scaleFrom: 100.0, + scaleTo: percent + }, arguments[2] || {}); + this.start(options); + }, + setup: function() { + this.restoreAfterFinish = this.options.restoreAfterFinish || false; + this.elementPositioning = this.element.getStyle('position'); + + this.originalStyle = {}; + ['top','left','width','height','fontSize'].each( function(k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this)); + + this.originalTop = this.element.offsetTop; + this.originalLeft = this.element.offsetLeft; + + var fontSize = this.element.getStyle('font-size') || '100%'; + ['em','px','%','pt'].each( function(fontSizeType) { + if(fontSize.indexOf(fontSizeType)>0) { + this.fontSize = parseFloat(fontSize); + this.fontSizeType = fontSizeType; + } + }.bind(this)); + + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; + + this.dims = null; + if(this.options.scaleMode=='box') + this.dims = [this.element.offsetHeight, this.element.offsetWidth]; + if(/^content/.test(this.options.scaleMode)) + this.dims = [this.element.scrollHeight, this.element.scrollWidth]; + if(!this.dims) + this.dims = [this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth]; + }, + update: function(position) { + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + if(this.options.scaleContent && this.fontSize) + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); + }, + finish: function(position) { + if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle); + }, + setDimensions: function(height, width) { + var d = {}; + if(this.options.scaleX) d.width = Math.round(width) + 'px'; + if(this.options.scaleY) d.height = Math.round(height) + 'px'; + if(this.options.scaleFromCenter) { + var topd = (height - this.dims[0])/2; + var leftd = (width - this.dims[1])/2; + if(this.elementPositioning == 'absolute') { + if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; + if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; + } else { + if(this.options.scaleY) d.top = -topd + 'px'; + if(this.options.scaleX) d.left = -leftd + 'px'; + } + } + this.element.setStyle(d); + } +}); + +Effect.Highlight = Class.create(); +Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {}); + this.start(options); + }, + setup: function() { + // Prevent executing on elements not in the layout flow + if(this.element.getStyle('display')=='none') { this.cancel(); return; } + // Disable background image during the effect + this.oldStyle = { + backgroundImage: this.element.getStyle('background-image') }; + this.element.setStyle({backgroundImage: 'none'}); + if(!this.options.endcolor) + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); + if(!this.options.restorecolor) + this.options.restorecolor = this.element.getStyle('background-color'); + // init color calculations + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); + this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); + }, + update: function(position) { + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ + return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) }); + }, + finish: function() { + this.element.setStyle(Object.extend(this.oldStyle, { + backgroundColor: this.options.restorecolor + })); + } +}); + +Effect.ScrollTo = Class.create(); +Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + this.start(arguments[1] || {}); + }, + setup: function() { + Position.prepare(); + var offsets = Position.cumulativeOffset(this.element); + if(this.options.offset) offsets[1] += this.options.offset; + var max = window.innerHeight ? + window.height - window.innerHeight : + document.body.scrollHeight - + (document.documentElement.clientHeight ? + document.documentElement.clientHeight : document.body.clientHeight); + this.scrollStart = Position.deltaY; + this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart; + }, + update: function(position) { + Position.prepare(); + window.scrollTo(Position.deltaX, + this.scrollStart + (position*this.delta)); + } +}); + +/* ------------- combination effects ------------- */ + +Effect.Fade = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + var options = Object.extend({ + from: element.getOpacity() || 1.0, + to: 0.0, + afterFinishInternal: function(effect) { + if(effect.options.to!=0) return; + effect.element.hide().setStyle({opacity: oldOpacity}); + }}, arguments[1] || {}); + return new Effect.Opacity(element,options); +} + +Effect.Appear = function(element) { + element = $(element); + var options = Object.extend({ + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), + to: 1.0, + // force Safari to render floated elements properly + afterFinishInternal: function(effect) { + effect.element.forceRerendering(); + }, + beforeSetup: function(effect) { + effect.element.setOpacity(effect.options.from).show(); + }}, arguments[1] || {}); + return new Effect.Opacity(element,options); +} + +Effect.Puff = function(element) { + element = $(element); + var oldStyle = { + opacity: element.getInlineOpacity(), + position: element.getStyle('position'), + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height + }; + return new Effect.Parallel( + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, + beforeSetupInternal: function(effect) { + Position.absolutize(effect.effects[0].element) + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().setStyle(oldStyle); } + }, arguments[1] || {}) + ); +} + +Effect.BlindUp = function(element) { + element = $(element); + element.makeClipping(); + return new Effect.Scale(element, 0, + Object.extend({ scaleContent: false, + scaleX: false, + restoreAfterFinish: true, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }, arguments[1] || {}) + ); +} + +Effect.BlindDown = function(element) { + element = $(element); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: 0, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + } + }, arguments[1] || {})); +} + +Effect.SwitchOff = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + return new Effect.Appear(element, Object.extend({ + duration: 0.4, + from: 0, + transition: Effect.Transitions.flicker, + afterFinishInternal: function(effect) { + new Effect.Scale(effect.element, 1, { + duration: 0.3, scaleFromCenter: true, + scaleX: false, scaleContent: false, restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); + } + }) + } + }, arguments[1] || {})); +} + +Effect.DropOut = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left'), + opacity: element.getInlineOpacity() }; + return new Effect.Parallel( + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 }) ], + Object.extend( + { duration: 0.5, + beforeSetup: function(effect) { + effect.effects[0].element.makePositioned(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); + } + }, arguments[1] || {})); +} + +Effect.Shake = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left') }; + return new Effect.Move(element, + { x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { + effect.element.undoPositioned().setStyle(oldStyle); + }}) }}) }}) }}) }}) }}); +} + +Effect.SlideDown = function(element) { + element = $(element).cleanWhitespace(); + // SlideDown need to have the content of the element wrapped in a container element with fixed height! + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: window.opera ? 0 : 1, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if(window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || {}) + ); +} + +Effect.SlideUp = function(element) { + element = $(element).cleanWhitespace(); + var oldInnerBottom = element.down().getStyle('bottom'); + return new Effect.Scale(element, window.opera ? 0 : 1, + Object.extend({ scaleContent: false, + scaleX: false, + scaleMode: 'box', + scaleFrom: 100, + restoreAfterFinish: true, + beforeStartInternal: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if(window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom}); + effect.element.down().undoPositioned(); + } + }, arguments[1] || {}) + ); +} + +// Bug in opera makes the TD containing this element expand for a instance after finish +Effect.Squish = function(element) { + return new Effect.Scale(element, window.opera ? 1 : 0, { + restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }); +} + +Effect.Grow = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.full + }, arguments[1] || {}); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var initialMoveX, initialMoveY; + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + initialMoveX = initialMoveY = moveX = moveY = 0; + break; + case 'top-right': + initialMoveX = dims.width; + initialMoveY = moveY = 0; + moveX = -dims.width; + break; + case 'bottom-left': + initialMoveX = moveX = 0; + initialMoveY = dims.height; + moveY = -dims.height; + break; + case 'bottom-right': + initialMoveX = dims.width; + initialMoveY = dims.height; + moveX = -dims.width; + moveY = -dims.height; + break; + case 'center': + initialMoveX = dims.width / 2; + initialMoveY = dims.height / 2; + moveX = -dims.width / 2; + moveY = -dims.height / 2; + break; + } + + return new Effect.Move(element, { + x: initialMoveX, + y: initialMoveY, + duration: 0.01, + beforeSetup: function(effect) { + effect.element.hide().makeClipping().makePositioned(); + }, + afterFinishInternal: function(effect) { + new Effect.Parallel( + [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), + new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), + new Effect.Scale(effect.element, 100, { + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) + ], Object.extend({ + beforeSetup: function(effect) { + effect.effects[0].element.setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); + } + }, options) + ) + } + }); +} + +Effect.Shrink = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.none + }, arguments[1] || {}); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + moveX = moveY = 0; + break; + case 'top-right': + moveX = dims.width; + moveY = 0; + break; + case 'bottom-left': + moveX = 0; + moveY = dims.height; + break; + case 'bottom-right': + moveX = dims.width; + moveY = dims.height; + break; + case 'center': + moveX = dims.width / 2; + moveY = dims.height / 2; + break; + } + + return new Effect.Parallel( + [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), + new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), + new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) + ], Object.extend({ + beforeStartInternal: function(effect) { + effect.effects[0].element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } + }, options) + ); +} + +Effect.Pulsate = function(element) { + element = $(element); + var options = arguments[1] || {}; + var oldOpacity = element.getInlineOpacity(); + var transition = options.transition || Effect.Transitions.sinoidal; + var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) }; + reverser.bind(transition); + return new Effect.Opacity(element, + Object.extend(Object.extend({ duration: 2.0, from: 0, + afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } + }, options), {transition: reverser})); +} + +Effect.Fold = function(element) { + element = $(element); + var oldStyle = { + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height }; + element.makeClipping(); + return new Effect.Scale(element, 5, Object.extend({ + scaleContent: false, + scaleX: false, + afterFinishInternal: function(effect) { + new Effect.Scale(element, 1, { + scaleContent: false, + scaleY: false, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().setStyle(oldStyle); + } }); + }}, arguments[1] || {})); +}; + +Effect.Morph = Class.create(); +Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + style: '' + }, arguments[1] || {}); + this.start(options); + }, + setup: function(){ + function parseColor(color){ + if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; + color = color.parseColor(); + return $R(0,2).map(function(i){ + return parseInt( color.slice(i*2+1,i*2+3), 16 ) + }); + } + this.transforms = this.options.style.parseStyle().map(function(property){ + var originalValue = this.element.getStyle(property[0]); + return $H({ + style: property[0], + originalValue: property[1].unit=='color' ? + parseColor(originalValue) : parseFloat(originalValue || 0), + targetValue: property[1].unit=='color' ? + parseColor(property[1].value) : property[1].value, + unit: property[1].unit + }); + }.bind(this)).reject(function(transform){ + return ( + (transform.originalValue == transform.targetValue) || + ( + transform.unit != 'color' && + (isNaN(transform.originalValue) || isNaN(transform.targetValue)) + ) + ) + }); + }, + update: function(position) { + var style = $H(), value = null; + this.transforms.each(function(transform){ + value = transform.unit=='color' ? + $R(0,2).inject('#',function(m,v,i){ + return m+(Math.round(transform.originalValue[i]+ + (transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) : + transform.originalValue + Math.round( + ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit; + style[transform.style] = value; + }); + this.element.setStyle(style); + } +}); + +Effect.Transform = Class.create(); +Object.extend(Effect.Transform.prototype, { + initialize: function(tracks){ + this.tracks = []; + this.options = arguments[1] || {}; + this.addTracks(tracks); + }, + addTracks: function(tracks){ + tracks.each(function(track){ + var data = $H(track).values().first(); + this.tracks.push($H({ + ids: $H(track).keys().first(), + effect: Effect.Morph, + options: { style: data } + })); + }.bind(this)); + return this; + }, + play: function(){ + return new Effect.Parallel( + this.tracks.map(function(track){ + var elements = [$(track.ids) || $$(track.ids)].flatten(); + return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) }); + }).flatten(), + this.options + ); + } +}); + +Element.CSS_PROPERTIES = ['azimuth', 'backgroundAttachment', 'backgroundColor', 'backgroundImage', + 'backgroundPosition', 'backgroundRepeat', 'borderBottomColor', 'borderBottomStyle', + 'borderBottomWidth', 'borderCollapse', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', + 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderSpacing', 'borderTopColor', + 'borderTopStyle', 'borderTopWidth', 'bottom', 'captionSide', 'clear', 'clip', 'color', 'content', + 'counterIncrement', 'counterReset', 'cssFloat', 'cueAfter', 'cueBefore', 'cursor', 'direction', + 'display', 'elevation', 'emptyCells', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', + 'fontStyle', 'fontVariant', 'fontWeight', 'height', 'left', 'letterSpacing', 'lineHeight', + 'listStyleImage', 'listStylePosition', 'listStyleType', 'marginBottom', 'marginLeft', 'marginRight', + 'marginTop', 'markerOffset', 'marks', 'maxHeight', 'maxWidth', 'minHeight', 'minWidth', 'opacity', + 'orphans', 'outlineColor', 'outlineOffset', 'outlineStyle', 'outlineWidth', 'overflowX', 'overflowY', + 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', 'page', 'pageBreakAfter', 'pageBreakBefore', + 'pageBreakInside', 'pauseAfter', 'pauseBefore', 'pitch', 'pitchRange', 'position', 'quotes', + 'richness', 'right', 'size', 'speakHeader', 'speakNumeral', 'speakPunctuation', 'speechRate', 'stress', + 'tableLayout', 'textAlign', 'textDecoration', 'textIndent', 'textShadow', 'textTransform', 'top', + 'unicodeBidi', 'verticalAlign', 'visibility', 'voiceFamily', 'volume', 'whiteSpace', 'widows', + 'width', 'wordSpacing', 'zIndex']; + +Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; + +String.prototype.parseStyle = function(){ + var element = Element.extend(document.createElement('div')); + element.innerHTML = '<div style="' + this + '"></div>'; + var style = element.down().style, styleRules = $H(); + + Element.CSS_PROPERTIES.each(function(property){ + if(style[property]) styleRules[property] = style[property]; + }); + + var result = $H(); + + styleRules.each(function(pair){ + var property = pair[0], value = pair[1], unit = null; + + if(value.parseColor('#zzzzzz') != '#zzzzzz') { + value = value.parseColor(); + unit = 'color'; + } else if(Element.CSS_LENGTH.test(value)) + var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/), + value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null; + + result[property.underscore().dasherize()] = $H({ value:value, unit:unit }); + }.bind(this)); + + return result; +}; + +Element.morph = function(element, style) { + new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {})); + return element; +}; + +['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom', + 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each( + function(f) { Element.Methods[f] = Element[f]; } +); + +Element.Methods.visualEffect = function(element, effect, options) { + s = effect.gsub(/_/, '-').camelize(); + effect_class = s.charAt(0).toUpperCase() + s.substring(1); + new Effect[effect_class](element, options); + return $(element); +}; + +Element.addMethods(); \ No newline at end of file diff --git a/public/javascripts/prototype.js b/public/javascripts/prototype.js new file mode 100644 index 0000000..5058221 --- /dev/null +++ b/public/javascripts/prototype.js @@ -0,0 +1,2515 @@ +/* Prototype JavaScript framework, version 1.5.0 + * (c) 2005-2007 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://prototype.conio.net/ + * +/*--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.5.0', + BrowserFeatures: { + XPath: !!document.evaluate + }, + + ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', + emptyFunction: function() {}, + K: function(x) { return x } +} + +var Class = { + create: function() { + return function() { + this.initialize.apply(this, arguments); + } + } +} + +var Abstract = new Object(); + +Object.extend = function(destination, source) { + for (var property in source) { + destination[property] = source[property]; + } + return destination; +} + +Object.extend(Object, { + inspect: function(object) { + try { + if (object === undefined) return 'undefined'; + if (object === null) return 'null'; + return object.inspect ? object.inspect() : object.toString(); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + }, + + keys: function(object) { + var keys = []; + for (var property in object) + keys.push(property); + return keys; + }, + + values: function(object) { + var values = []; + for (var property in object) + values.push(object[property]); + return values; + }, + + clone: function(object) { + return Object.extend({}, object); + } +}); + +Function.prototype.bind = function() { + var __method = this, args = $A(arguments), object = args.shift(); + return function() { + return __method.apply(object, args.concat($A(arguments))); + } +} + +Function.prototype.bindAsEventListener = function(object) { + var __method = this, args = $A(arguments), object = args.shift(); + return function(event) { + return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments))); + } +} + +Object.extend(Number.prototype, { + toColorPart: function() { + var digits = this.toString(16); + if (this < 16) return '0' + digits; + return digits; + }, + + succ: function() { + return this + 1; + }, + + times: function(iterator) { + $R(0, this, true).each(iterator); + return this; + } +}); + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) {} + } + + return returnValue; + } +} + +/*--------------------------------------------------------------------------*/ + +var PeriodicalExecuter = Class.create(); +PeriodicalExecuter.prototype = { + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.callback(this); + } finally { + this.currentlyExecuting = false; + } + } + } +} +String.interpret = function(value){ + return value == null ? '' : String(value); +} + +Object.extend(String.prototype, { + gsub: function(pattern, replacement) { + var result = '', source = this, match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + + sub: function(pattern, replacement, count) { + replacement = this.gsub.prepareReplacement(replacement); + count = count === undefined ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + }, + + scan: function(pattern, iterator) { + this.gsub(pattern, iterator); + return this; + }, + + truncate: function(length, truncation) { + length = length || 30; + truncation = truncation === undefined ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : this; + }, + + strip: function() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + }, + + stripTags: function() { + return this.replace(/<\/?[^>]+>/gi, ''); + }, + + stripScripts: function() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + }, + + extractScripts: function() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + }, + + evalScripts: function() { + return this.extractScripts().map(function(script) { return eval(script) }); + }, + + escapeHTML: function() { + var div = document.createElement('div'); + var text = document.createTextNode(this); + div.appendChild(text); + return div.innerHTML; + }, + + unescapeHTML: function() { + var div = document.createElement('div'); + div.innerHTML = this.stripTags(); + return div.childNodes[0] ? (div.childNodes.length > 1 ? + $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) : + div.childNodes[0].nodeValue) : ''; + }, + + toQueryParams: function(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return {}; + + return match[1].split(separator || '&').inject({}, function(hash, pair) { + if ((pair = pair.split('='))[0]) { + var name = decodeURIComponent(pair[0]); + var value = pair[1] ? decodeURIComponent(pair[1]) : undefined; + + if (hash[name] !== undefined) { + if (hash[name].constructor != Array) + hash[name] = [hash[name]]; + if (value) hash[name].push(value); + } + else hash[name] = value; + } + return hash; + }); + }, + + toArray: function() { + return this.split(''); + }, + + succ: function() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + }, + + camelize: function() { + var parts = this.split('-'), len = parts.length; + if (len == 1) return parts[0]; + + var camelized = this.charAt(0) == '-' + ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) + : parts[0]; + + for (var i = 1; i < len; i++) + camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + + return camelized; + }, + + capitalize: function(){ + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + }, + + underscore: function() { + return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); + }, + + dasherize: function() { + return this.gsub(/_/,'-'); + }, + + inspect: function(useDoubleQuotes) { + var escapedString = this.replace(/\\/g, '\\\\'); + if (useDoubleQuotes) + return '"' + escapedString.replace(/"/g, '\\"') + '"'; + else + return "'" + escapedString.replace(/'/g, '\\\'') + "'"; + } +}); + +String.prototype.gsub.prepareReplacement = function(replacement) { + if (typeof replacement == 'function') return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +} + +String.prototype.parseQuery = String.prototype.toQueryParams; + +var Template = Class.create(); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; +Template.prototype = { + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + return this.template.gsub(this.pattern, function(match) { + var before = match[1]; + if (before == '\\') return match[2]; + return before + String.interpret(object[match[3]]); + }); + } +} + +var $break = new Object(); +var $continue = new Object(); + +var Enumerable = { + each: function(iterator) { + var index = 0; + try { + this._each(function(value) { + try { + iterator(value, index++); + } catch (e) { + if (e != $continue) throw e; + } + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + }, + + eachSlice: function(number, iterator) { + var index = -number, slices = [], array = this.toArray(); + while ((index += number) < array.length) + slices.push(array.slice(index, index+number)); + return slices.map(iterator); + }, + + all: function(iterator) { + var result = true; + this.each(function(value, index) { + result = result && !!(iterator || Prototype.K)(value, index); + if (!result) throw $break; + }); + return result; + }, + + any: function(iterator) { + var result = false; + this.each(function(value, index) { + if (result = !!(iterator || Prototype.K)(value, index)) + throw $break; + }); + return result; + }, + + collect: function(iterator) { + var results = []; + this.each(function(value, index) { + results.push((iterator || Prototype.K)(value, index)); + }); + return results; + }, + + detect: function(iterator) { + var result; + this.each(function(value, index) { + if (iterator(value, index)) { + result = value; + throw $break; + } + }); + return result; + }, + + findAll: function(iterator) { + var results = []; + this.each(function(value, index) { + if (iterator(value, index)) + results.push(value); + }); + return results; + }, + + grep: function(pattern, iterator) { + var results = []; + this.each(function(value, index) { + var stringValue = value.toString(); + if (stringValue.match(pattern)) + results.push((iterator || Prototype.K)(value, index)); + }) + return results; + }, + + include: function(object) { + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + }, + + inGroupsOf: function(number, fillWith) { + fillWith = fillWith === undefined ? null : fillWith; + return this.eachSlice(number, function(slice) { + while(slice.length < number) slice.push(fillWith); + return slice; + }); + }, + + inject: function(memo, iterator) { + this.each(function(value, index) { + memo = iterator(memo, value, index); + }); + return memo; + }, + + invoke: function(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + }, + + max: function(iterator) { + var result; + this.each(function(value, index) { + value = (iterator || Prototype.K)(value, index); + if (result == undefined || value >= result) + result = value; + }); + return result; + }, + + min: function(iterator) { + var result; + this.each(function(value, index) { + value = (iterator || Prototype.K)(value, index); + if (result == undefined || value < result) + result = value; + }); + return result; + }, + + partition: function(iterator) { + var trues = [], falses = []; + this.each(function(value, index) { + ((iterator || Prototype.K)(value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + }, + + pluck: function(property) { + var results = []; + this.each(function(value, index) { + results.push(value[property]); + }); + return results; + }, + + reject: function(iterator) { + var results = []; + this.each(function(value, index) { + if (!iterator(value, index)) + results.push(value); + }); + return results; + }, + + sortBy: function(iterator) { + return this.map(function(value, index) { + return {value: value, criteria: iterator(value, index)}; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + }, + + toArray: function() { + return this.map(); + }, + + zip: function() { + var iterator = Prototype.K, args = $A(arguments); + if (typeof args.last() == 'function') + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + }, + + size: function() { + return this.toArray().length; + }, + + inspect: function() { + return '#<Enumerable:' + this.toArray().inspect() + '>'; + } +} + +Object.extend(Enumerable, { + map: Enumerable.collect, + find: Enumerable.detect, + select: Enumerable.findAll, + member: Enumerable.include, + entries: Enumerable.toArray +}); +var $A = Array.from = function(iterable) { + if (!iterable) return []; + if (iterable.toArray) { + return iterable.toArray(); + } else { + var results = []; + for (var i = 0, length = iterable.length; i < length; i++) + results.push(iterable[i]); + return results; + } +} + +Object.extend(Array.prototype, Enumerable); + +if (!Array.prototype._reverse) + Array.prototype._reverse = Array.prototype.reverse; + +Object.extend(Array.prototype, { + _each: function(iterator) { + for (var i = 0, length = this.length; i < length; i++) + iterator(this[i]); + }, + + clear: function() { + this.length = 0; + return this; + }, + + first: function() { + return this[0]; + }, + + last: function() { + return this[this.length - 1]; + }, + + compact: function() { + return this.select(function(value) { + return value != null; + }); + }, + + flatten: function() { + return this.inject([], function(array, value) { + return array.concat(value && value.constructor == Array ? + value.flatten() : [value]); + }); + }, + + without: function() { + var values = $A(arguments); + return this.select(function(value) { + return !values.include(value); + }); + }, + + indexOf: function(object) { + for (var i = 0, length = this.length; i < length; i++) + if (this[i] == object) return i; + return -1; + }, + + reverse: function(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + }, + + reduce: function() { + return this.length > 1 ? this : this[0]; + }, + + uniq: function() { + return this.inject([], function(array, value) { + return array.include(value) ? array : array.concat([value]); + }); + }, + + clone: function() { + return [].concat(this); + }, + + size: function() { + return this.length; + }, + + inspect: function() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + } +}); + +Array.prototype.toArray = Array.prototype.clone; + +function $w(string){ + string = string.strip(); + return string ? string.split(/\s+/) : []; +} + +if(window.opera){ + Array.prototype.concat = function(){ + var array = []; + for(var i = 0, length = this.length; i < length; i++) array.push(this[i]); + for(var i = 0, length = arguments.length; i < length; i++) { + if(arguments[i].constructor == Array) { + for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) + array.push(arguments[i][j]); + } else { + array.push(arguments[i]); + } + } + return array; + } +} +var Hash = function(obj) { + Object.extend(this, obj || {}); +}; + +Object.extend(Hash, { + toQueryString: function(obj) { + var parts = []; + + this.prototype._each.call(obj, function(pair) { + if (!pair.key) return; + + if (pair.value && pair.value.constructor == Array) { + var values = pair.value.compact(); + if (values.length < 2) pair.value = values.reduce(); + else { + key = encodeURIComponent(pair.key); + values.each(function(value) { + value = value != undefined ? encodeURIComponent(value) : ''; + parts.push(key + '=' + encodeURIComponent(value)); + }); + return; + } + } + if (pair.value == undefined) pair[1] = ''; + parts.push(pair.map(encodeURIComponent).join('=')); + }); + + return parts.join('&'); + } +}); + +Object.extend(Hash.prototype, Enumerable); +Object.extend(Hash.prototype, { + _each: function(iterator) { + for (var key in this) { + var value = this[key]; + if (value && value == Hash.prototype[key]) continue; + + var pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + }, + + keys: function() { + return this.pluck('key'); + }, + + values: function() { + return this.pluck('value'); + }, + + merge: function(hash) { + return $H(hash).inject(this, function(mergedHash, pair) { + mergedHash[pair.key] = pair.value; + return mergedHash; + }); + }, + + remove: function() { + var result; + for(var i = 0, length = arguments.length; i < length; i++) { + var value = this[arguments[i]]; + if (value !== undefined){ + if (result === undefined) result = value; + else { + if (result.constructor != Array) result = [result]; + result.push(value) + } + } + delete this[arguments[i]]; + } + return result; + }, + + toQueryString: function() { + return Hash.toQueryString(this); + }, + + inspect: function() { + return '#<Hash:{' + this.map(function(pair) { + return pair.map(Object.inspect).join(': '); + }).join(', ') + '}>'; + } +}); + +function $H(object) { + if (object && object.constructor == Hash) return object; + return new Hash(object); +}; +ObjectRange = Class.create(); +Object.extend(ObjectRange.prototype, Enumerable); +Object.extend(ObjectRange.prototype, { + initialize: function(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + }, + + _each: function(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + }, + + include: function(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } +}); + +var $R = function(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +} + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +} + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(responder); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (typeof responder[callback] == 'function') { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) {} + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { + Ajax.activeRequestCount++; + }, + onComplete: function() { + Ajax.activeRequestCount--; + } +}); + +Ajax.Base = function() {}; +Ajax.Base.prototype = { + setOptions: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '' + } + Object.extend(this.options, options || {}); + + this.options.method = this.options.method.toLowerCase(); + if (typeof this.options.parameters == 'string') + this.options.parameters = this.options.parameters.toQueryParams(); + } +} + +Ajax.Request = Class.create(); +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + +Ajax.Request.prototype = Object.extend(new Ajax.Base(), { + _complete: false, + + initialize: function(url, options) { + this.transport = Ajax.getTransport(); + this.setOptions(options); + this.request(url); + }, + + request: function(url) { + this.url = url; + this.method = this.options.method; + var params = this.options.parameters; + + if (!['get', 'post'].include(this.method)) { + // simulate other verbs over post + params['_method'] = this.method; + this.method = 'post'; + } + + params = Hash.toQueryString(params); + if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_=' + + // when GET, append parameters to URL + if (this.method == 'get' && params) + this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params; + + try { + Ajax.Responders.dispatch('onCreate', this, this.transport); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + if (this.options.asynchronous) + setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10); + + this.transport.onreadystatechange = this.onStateChange.bind(this); + this.setRequestHeaders(); + + var body = this.method == 'post' ? (this.options.postBody || params) : null; + + this.transport.send(body); + + /* Force Firefox to handle ready state 4 for synchronous requests */ + if (!this.options.asynchronous && this.transport.overrideMimeType) + this.onStateChange(); + + } + catch (e) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + 'X-Requested-With': 'XMLHttpRequest', + 'X-Prototype-Version': Prototype.Version, + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }; + + if (this.method == 'post') { + headers['Content-type'] = this.options.contentType + + (this.options.encoding ? '; charset=' + this.options.encoding : ''); + + /* Force "Connection: close" for older Mozilla browsers to work + * around a bug where XMLHttpRequest sends an incorrect + * Content-length header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) + headers['Connection'] = 'close'; + } + + // user-defined headers + if (typeof this.options.requestHeaders == 'object') { + var extras = this.options.requestHeaders; + + if (typeof extras.push == 'function') + for (var i = 0, length = extras.length; i < length; i += 2) + headers[extras[i]] = extras[i+1]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + return !this.transport.status + || (this.transport.status >= 200 && this.transport.status < 300); + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState]; + var transport = this.transport, json = this.evalJSON(); + + if (state == 'Complete') { + try { + this._complete = true; + (this.options['on' + this.transport.status] + || this.options['on' + (this.success() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(transport, json); + } catch (e) { + this.dispatchException(e); + } + + if ((this.getHeader('Content-type') || 'text/javascript').strip(). + match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) + this.evalResponse(); + } + + try { + (this.options['on' + state] || Prototype.emptyFunction)(transport, json); + Ajax.Responders.dispatch('on' + state, this, transport, json); + } catch (e) { + this.dispatchException(e); + } + + if (state == 'Complete') { + // avoid memory leak in MSIE: clean up + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name); + } catch (e) { return null } + }, + + evalJSON: function() { + try { + var json = this.getHeader('X-JSON'); + return json ? eval('(' + json + ')') : null; + } catch (e) { return null } + }, + + evalResponse: function() { + try { + return eval(this.transport.responseText); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Updater = Class.create(); + +Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { + initialize: function(container, url, options) { + this.container = { + success: (container.success || container), + failure: (container.failure || (container.success ? null : container)) + } + + this.transport = Ajax.getTransport(); + this.setOptions(options); + + var onComplete = this.options.onComplete || Prototype.emptyFunction; + this.options.onComplete = (function(transport, param) { + this.updateContent(); + onComplete(transport, param); + }).bind(this); + + this.request(url); + }, + + updateContent: function() { + var receiver = this.container[this.success() ? 'success' : 'failure']; + var response = this.transport.responseText; + + if (!this.options.evalScripts) response = response.stripScripts(); + + if (receiver = $(receiver)) { + if (this.options.insertion) + new this.options.insertion(receiver, response); + else + receiver.update(response); + } + + if (this.success()) { + if (this.onComplete) + setTimeout(this.onComplete.bind(this), 10); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(); +Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { + initialize: function(container, url, options) { + this.setOptions(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = {}; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(request) { + if (this.options.decay) { + this.decay = (request.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = request.responseText; + } + this.timer = setTimeout(this.onTimerEvent.bind(this), + this.decay * this.frequency * 1000); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); +function $(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push($(arguments[i])); + return elements; + } + if (typeof element == 'string') + element = document.getElementById(element); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + var query = document.evaluate(expression, $(parentElement) || document, + null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0, length = query.snapshotLength; i < length; i++) + results.push(query.snapshotItem(i)); + return results; + }; +} + +document.getElementsByClassName = function(className, parentElement) { + if (Prototype.BrowserFeatures.XPath) { + var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]"; + return document._getElementsByXPath(q, parentElement); + } else { + var children = ($(parentElement) || document.body).getElementsByTagName('*'); + var elements = [], child; + for (var i = 0, length = children.length; i < length; i++) { + child = children[i]; + if (Element.hasClassName(child, className)) + elements.push(Element.extend(child)); + } + return elements; + } +}; + +/*--------------------------------------------------------------------------*/ + +if (!window.Element) + var Element = new Object(); + +Element.extend = function(element) { + if (!element || _nativeExtensions || element.nodeType == 3) return element; + + if (!element._extended && element.tagName && element != window) { + var methods = Object.clone(Element.Methods), cache = Element.extend.cache; + + if (element.tagName == 'FORM') + Object.extend(methods, Form.Methods); + if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName)) + Object.extend(methods, Form.Element.Methods); + + Object.extend(methods, Element.Methods.Simulated); + + for (var property in methods) { + var value = methods[property]; + if (typeof value == 'function' && !(property in element)) + element[property] = cache.findOrStore(value); + } + } + + element._extended = true; + return element; +}; + +Element.extend.cache = { + findOrStore: function(value) { + return this[value] = this[value] || function() { + return value.apply(null, [this].concat($A(arguments))); + } + } +}; + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + hide: function(element) { + $(element).style.display = 'none'; + return element; + }, + + show: function(element) { + $(element).style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: function(element, html) { + html = typeof html == 'undefined' ? '' : html.toString(); + $(element).innerHTML = html.stripScripts(); + setTimeout(function() {html.evalScripts()}, 10); + return element; + }, + + replace: function(element, html) { + element = $(element); + html = typeof html == 'undefined' ? '' : html.toString(); + if (element.outerHTML) { + element.outerHTML = html.stripScripts(); + } else { + var range = element.ownerDocument.createRange(); + range.selectNodeContents(element); + element.parentNode.replaceChild( + range.createContextualFragment(html.stripScripts()), element); + } + setTimeout(function() {html.evalScripts()}, 10); + return element; + }, + + inspect: function(element) { + element = $(element); + var result = '<' + element.tagName.toLowerCase(); + $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var property = pair.first(), attribute = pair.last(); + var value = (element[property] || '').toString(); + if (value) result += ' ' + attribute + '=' + value.inspect(true); + }); + return result + '>'; + }, + + recursivelyCollect: function(element, property) { + element = $(element); + var elements = []; + while (element = element[property]) + if (element.nodeType == 1) + elements.push(Element.extend(element)); + return elements; + }, + + ancestors: function(element) { + return $(element).recursivelyCollect('parentNode'); + }, + + descendants: function(element) { + return $A($(element).getElementsByTagName('*')); + }, + + immediateDescendants: function(element) { + if (!(element = $(element).firstChild)) return []; + while (element && element.nodeType != 1) element = element.nextSibling; + if (element) return [element].concat($(element).nextSiblings()); + return []; + }, + + previousSiblings: function(element) { + return $(element).recursivelyCollect('previousSibling'); + }, + + nextSiblings: function(element) { + return $(element).recursivelyCollect('nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return element.previousSiblings().reverse().concat(element.nextSiblings()); + }, + + match: function(element, selector) { + if (typeof selector == 'string') + selector = new Selector(selector); + return selector.match($(element)); + }, + + up: function(element, expression, index) { + return Selector.findElement($(element).ancestors(), expression, index); + }, + + down: function(element, expression, index) { + return Selector.findElement($(element).descendants(), expression, index); + }, + + previous: function(element, expression, index) { + return Selector.findElement($(element).previousSiblings(), expression, index); + }, + + next: function(element, expression, index) { + return Selector.findElement($(element).nextSiblings(), expression, index); + }, + + getElementsBySelector: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element, args); + }, + + getElementsByClassName: function(element, className) { + return document.getElementsByClassName(className, element); + }, + + readAttribute: function(element, name) { + element = $(element); + if (document.all && !window.opera) { + var t = Element._attributeTranslations; + if (t.values[name]) return t.values[name](element, name); + if (t.names[name]) name = t.names[name]; + var attribute = element.attributes[name]; + if(attribute) return attribute.nodeValue; + } + return element.getAttribute(name); + }, + + getHeight: function(element) { + return $(element).getDimensions().height; + }, + + getWidth: function(element) { + return $(element).getDimensions().width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + var elementClassName = element.className; + if (elementClassName.length == 0) return false; + if (elementClassName == className || + elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) + return true; + return false; + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + Element.classNames(element).add(className); + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + Element.classNames(element).remove(className); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className); + return element; + }, + + observe: function() { + Event.observe.apply(Event, arguments); + return $A(arguments).first(); + }, + + stopObserving: function() { + Event.stopObserving.apply(Event, arguments); + return $A(arguments).first(); + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.match(/^\s*$/); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + while (element = element.parentNode) + if (element == ancestor) return true; + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = Position.cumulativeOffset(element); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + if (['float','cssFloat'].include(style)) + style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat'); + style = style.camelize(); + var value = element.style[style]; + if (!value) { + if (document.defaultView && document.defaultView.getComputedStyle) { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css[style] : null; + } else if (element.currentStyle) { + value = element.currentStyle[style]; + } + } + + if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none')) + value = element['offset'+style.capitalize()] + 'px'; + + if (window.opera && ['left', 'top', 'right', 'bottom'].include(style)) + if (Element.getStyle(element, 'position') == 'static') value = 'auto'; + if(style == 'opacity') { + if(value) return parseFloat(value); + if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if(value[1]) return parseFloat(value[1]) / 100; + return 1.0; + } + return value == 'auto' ? null : value; + }, + + setStyle: function(element, style) { + element = $(element); + for (var name in style) { + var value = style[name]; + if(name == 'opacity') { + if (value == 1) { + value = (/Gecko/.test(navigator.userAgent) && + !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0; + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); + } else if(value == '') { + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); + } else { + if(value < 0.00001) value = 0; + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') + + 'alpha(opacity='+value*100+')'; + } + } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat'; + element.style[name.camelize()] = value; + } + return element; + }, + + getDimensions: function(element) { + element = $(element); + var display = $(element).getStyle('display'); + if (display != 'none' && display != null) // Safari bug + return {width: element.offsetWidth, height: element.offsetHeight}; + + // All *Width and *Height properties give 0 on elements with display none, + // so enable the element temporarily + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + var originalDisplay = els.display; + els.visibility = 'hidden'; + els.position = 'absolute'; + els.display = 'block'; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = originalDisplay; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + // Opera returns the offset relative to the positioning context, when an + // element is position relative but top and left have not been defined + if (window.opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return element; + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return element; + element._overflow = element.style.overflow || 'auto'; + if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden') + element.style.overflow = 'hidden'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element._overflow = null; + return element; + } +}; + +Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf}); + +Element._attributeTranslations = {}; + +Element._attributeTranslations.names = { + colspan: "colSpan", + rowspan: "rowSpan", + valign: "vAlign", + datetime: "dateTime", + accesskey: "accessKey", + tabindex: "tabIndex", + enctype: "encType", + maxlength: "maxLength", + readonly: "readOnly", + longdesc: "longDesc" +}; + +Element._attributeTranslations.values = { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + + title: function(element) { + var node = element.getAttributeNode('title'); + return node.specified ? node.nodeValue : null; + } +}; + +Object.extend(Element._attributeTranslations.values, { + href: Element._attributeTranslations.values._getAttr, + src: Element._attributeTranslations.values._getAttr, + disabled: Element._attributeTranslations.values._flag, + checked: Element._attributeTranslations.values._flag, + readonly: Element._attributeTranslations.values._flag, + multiple: Element._attributeTranslations.values._flag +}); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + var t = Element._attributeTranslations; + attribute = t.names[attribute] || attribute; + return $(element).getAttributeNode(attribute).specified; + } +}; + +// IE is missing .innerHTML support for TABLE-related elements +if (document.all && !window.opera){ + Element.Methods.update = function(element, html) { + element = $(element); + html = typeof html == 'undefined' ? '' : html.toString(); + var tagName = element.tagName.toUpperCase(); + if (['THEAD','TBODY','TR','TD'].include(tagName)) { + var div = document.createElement('div'); + switch (tagName) { + case 'THEAD': + case 'TBODY': + div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>'; + depth = 2; + break; + case 'TR': + div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>'; + depth = 3; + break; + case 'TD': + div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>'; + depth = 4; + } + $A(element.childNodes).each(function(node){ + element.removeChild(node) + }); + depth.times(function(){ div = div.firstChild }); + + $A(div.childNodes).each( + function(node){ element.appendChild(node) }); + } else { + element.innerHTML = html.stripScripts(); + } + setTimeout(function() {html.evalScripts()}, 10); + return element; + } +}; + +Object.extend(Element, Element.Methods); + +var _nativeExtensions = false; + +if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)) + ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) { + var className = 'HTML' + tag + 'Element'; + if(window[className]) return; + var klass = window[className] = {}; + klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__; + }); + +Element.addMethods = function(methods) { + Object.extend(Element.Methods, methods || {}); + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + var cache = Element.extend.cache; + for (var property in methods) { + var value = methods[property]; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = cache.findOrStore(value); + } + } + + if (typeof HTMLElement != 'undefined') { + copy(Element.Methods, HTMLElement.prototype); + copy(Element.Methods.Simulated, HTMLElement.prototype, true); + copy(Form.Methods, HTMLFormElement.prototype); + [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) { + copy(Form.Element.Methods, klass.prototype); + }); + _nativeExtensions = true; + } +} + +var Toggle = new Object(); +Toggle.display = Element.toggle; + +/*--------------------------------------------------------------------------*/ + +Abstract.Insertion = function(adjacency) { + this.adjacency = adjacency; +} + +Abstract.Insertion.prototype = { + initialize: function(element, content) { + this.element = $(element); + this.content = content.stripScripts(); + + if (this.adjacency && this.element.insertAdjacentHTML) { + try { + this.element.insertAdjacentHTML(this.adjacency, this.content); + } catch (e) { + var tagName = this.element.tagName.toUpperCase(); + if (['TBODY', 'TR'].include(tagName)) { + this.insertContent(this.contentFromAnonymousTable()); + } else { + throw e; + } + } + } else { + this.range = this.element.ownerDocument.createRange(); + if (this.initializeRange) this.initializeRange(); + this.insertContent([this.range.createContextualFragment(this.content)]); + } + + setTimeout(function() {content.evalScripts()}, 10); + }, + + contentFromAnonymousTable: function() { + var div = document.createElement('div'); + div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>'; + return $A(div.childNodes[0].childNodes[0].childNodes); + } +} + +var Insertion = new Object(); + +Insertion.Before = Class.create(); +Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), { + initializeRange: function() { + this.range.setStartBefore(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.parentNode.insertBefore(fragment, this.element); + }).bind(this)); + } +}); + +Insertion.Top = Class.create(); +Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), { + initializeRange: function() { + this.range.selectNodeContents(this.element); + this.range.collapse(true); + }, + + insertContent: function(fragments) { + fragments.reverse(false).each((function(fragment) { + this.element.insertBefore(fragment, this.element.firstChild); + }).bind(this)); + } +}); + +Insertion.Bottom = Class.create(); +Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), { + initializeRange: function() { + this.range.selectNodeContents(this.element); + this.range.collapse(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.appendChild(fragment); + }).bind(this)); + } +}); + +Insertion.After = Class.create(); +Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), { + initializeRange: function() { + this.range.setStartAfter(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.parentNode.insertBefore(fragment, + this.element.nextSibling); + }).bind(this)); + } +}); + +/*--------------------------------------------------------------------------*/ + +Element.ClassNames = Class.create(); +Element.ClassNames.prototype = { + initialize: function(element) { + this.element = $(element); + }, + + _each: function(iterator) { + this.element.className.split(/\s+/).select(function(name) { + return name.length > 0; + })._each(iterator); + }, + + set: function(className) { + this.element.className = className; + }, + + add: function(classNameToAdd) { + if (this.include(classNameToAdd)) return; + this.set($A(this).concat(classNameToAdd).join(' ')); + }, + + remove: function(classNameToRemove) { + if (!this.include(classNameToRemove)) return; + this.set($A(this).without(classNameToRemove).join(' ')); + }, + + toString: function() { + return $A(this).join(' '); + } +}; + +Object.extend(Element.ClassNames.prototype, Enumerable); +var Selector = Class.create(); +Selector.prototype = { + initialize: function(expression) { + this.params = {classNames: []}; + this.expression = expression.toString().strip(); + this.parseExpression(); + this.compileMatcher(); + }, + + parseExpression: function() { + function abort(message) { throw 'Parse error in selector: ' + message; } + + if (this.expression == '') abort('empty expression'); + + var params = this.params, expr = this.expression, match, modifier, clause, rest; + while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) { + params.attributes = params.attributes || []; + params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''}); + expr = match[1]; + } + + if (expr == '*') return this.params.wildcard = true; + + while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) { + modifier = match[1], clause = match[2], rest = match[3]; + switch (modifier) { + case '#': params.id = clause; break; + case '.': params.classNames.push(clause); break; + case '': + case undefined: params.tagName = clause.toUpperCase(); break; + default: abort(expr.inspect()); + } + expr = rest; + } + + if (expr.length > 0) abort(expr.inspect()); + }, + + buildMatchExpression: function() { + var params = this.params, conditions = [], clause; + + if (params.wildcard) + conditions.push('true'); + if (clause = params.id) + conditions.push('element.readAttribute("id") == ' + clause.inspect()); + if (clause = params.tagName) + conditions.push('element.tagName.toUpperCase() == ' + clause.inspect()); + if ((clause = params.classNames).length > 0) + for (var i = 0, length = clause.length; i < length; i++) + conditions.push('element.hasClassName(' + clause[i].inspect() + ')'); + if (clause = params.attributes) { + clause.each(function(attribute) { + var value = 'element.readAttribute(' + attribute.name.inspect() + ')'; + var splitValueBy = function(delimiter) { + return value + ' && ' + value + '.split(' + delimiter.inspect() + ')'; + } + + switch (attribute.operator) { + case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break; + case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break; + case '|=': conditions.push( + splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect() + ); break; + case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break; + case '': + case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break; + default: throw 'Unknown operator ' + attribute.operator + ' in selector'; + } + }); + } + + return conditions.join(' && '); + }, + + compileMatcher: function() { + this.match = new Function('element', 'if (!element.tagName) return false; \ + element = $(element); \ + return ' + this.buildMatchExpression()); + }, + + findElements: function(scope) { + var element; + + if (element = $(this.params.id)) + if (this.match(element)) + if (!scope || Element.childOf(element, scope)) + return [element]; + + scope = (scope || document).getElementsByTagName(this.params.tagName || '*'); + + var results = []; + for (var i = 0, length = scope.length; i < length; i++) + if (this.match(element = scope[i])) + results.push(Element.extend(element)); + + return results; + }, + + toString: function() { + return this.expression; + } +} + +Object.extend(Selector, { + matchElements: function(elements, expression) { + var selector = new Selector(expression); + return elements.select(selector.match.bind(selector)).map(Element.extend); + }, + + findElement: function(elements, expression, index) { + if (typeof expression == 'number') index = expression, expression = false; + return Selector.matchElements(elements, expression || '*')[index || 0]; + }, + + findChildElements: function(element, expressions) { + return expressions.map(function(expression) { + return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) { + var selector = new Selector(expr); + return results.inject([], function(elements, result) { + return elements.concat(selector.findElements(result || element)); + }); + }); + }).flatten(); + } +}); + +function $$() { + return Selector.findChildElements(document, $A(arguments)); +} +var Form = { + reset: function(form) { + $(form).reset(); + return form; + }, + + serializeElements: function(elements, getHash) { + var data = elements.inject({}, function(result, element) { + if (!element.disabled && element.name) { + var key = element.name, value = $(element).getValue(); + if (value != undefined) { + if (result[key]) { + if (result[key].constructor != Array) result[key] = [result[key]]; + result[key].push(value); + } + else result[key] = value; + } + } + return result; + }); + + return getHash ? data : Hash.toQueryString(data); + } +}; + +Form.Methods = { + serialize: function(form, getHash) { + return Form.serializeElements(Form.getElements(form), getHash); + }, + + getElements: function(form) { + return $A($(form).getElementsByTagName('*')).inject([], + function(elements, child) { + if (Form.Element.Serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + } + ); + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) return $A(inputs).map(Element.extend); + + for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + form.getElements().each(function(element) { + element.blur(); + element.disabled = 'true'; + }); + return form; + }, + + enable: function(form) { + form = $(form); + form.getElements().each(function(element) { + element.disabled = ''; + }); + return form; + }, + + findFirstElement: function(form) { + return $(form).getElements().find(function(element) { + return element.type != 'hidden' && !element.disabled && + ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + }); + }, + + focusFirstElement: function(form) { + form = $(form); + form.findFirstElement().activate(); + return form; + } +} + +Object.extend(Form, Form.Methods); + +/*--------------------------------------------------------------------------*/ + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +} + +Form.Element.Methods = { + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = {}; + pair[element.name] = value; + return Hash.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + element.focus(); + if (element.select && ( element.tagName.toLowerCase() != 'input' || + !['button', 'reset', 'submit'].include(element.type) ) ) + element.select(); + return element; + }, + + disable: function(element) { + element = $(element); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.blur(); + element.disabled = false; + return element; + } +} + +Object.extend(Form.Element, Form.Element.Methods); +var Field = Form.Element; +var $F = Form.Element.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = { + input: function(element) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element); + default: + return Form.Element.Serializers.textarea(element); + } + }, + + inputSelector: function(element) { + return element.checked ? element.value : null; + }, + + textarea: function(element) { + return element.value; + }, + + select: function(element) { + return this[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + }, + + selectOne: function(element) { + var index = element.selectedIndex; + return index >= 0 ? this.optionValue(element.options[index]) : null; + }, + + selectMany: function(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(this.optionValue(opt)); + } + return values; + }, + + optionValue: function(opt) { + // extend element because hasAttribute may not be native + return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + } +} + +/*--------------------------------------------------------------------------*/ + +Abstract.TimedObserver = function() {} +Abstract.TimedObserver.prototype = { + initialize: function(element, frequency, callback) { + this.frequency = frequency; + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + this.registerCallback(); + }, + + registerCallback: function() { + setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + onTimerEvent: function() { + var value = this.getValue(); + var changed = ('string' == typeof this.lastValue && 'string' == typeof value + ? this.lastValue != value : String(this.lastValue) != String(value)); + if (changed) { + this.callback(this.element, value); + this.lastValue = value; + } + } +} + +Form.Element.Observer = Class.create(); +Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(); +Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = function() {} +Abstract.EventObserver.prototype = { + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback.bind(this)); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +} + +Form.Element.EventObserver = Class.create(); +Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(); +Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { + getValue: function() { + return Form.serialize(this.element); + } +}); +if (!window.Event) { + var Event = new Object(); +} + +Object.extend(Event, { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + + element: function(event) { + return event.target || event.srcElement; + }, + + isLeftClick: function(event) { + return (((event.which) && (event.which == 1)) || + ((event.button) && (event.button == 1))); + }, + + pointerX: function(event) { + return event.pageX || (event.clientX + + (document.documentElement.scrollLeft || document.body.scrollLeft)); + }, + + pointerY: function(event) { + return event.pageY || (event.clientY + + (document.documentElement.scrollTop || document.body.scrollTop)); + }, + + stop: function(event) { + if (event.preventDefault) { + event.preventDefault(); + event.stopPropagation(); + } else { + event.returnValue = false; + event.cancelBubble = true; + } + }, + + // find the first node with the given tagName, starting from the + // node the event was triggered on; traverses the DOM upwards + findElement: function(event, tagName) { + var element = Event.element(event); + while (element.parentNode && (!element.tagName || + (element.tagName.toUpperCase() != tagName.toUpperCase()))) + element = element.parentNode; + return element; + }, + + observers: false, + + _observeAndCache: function(element, name, observer, useCapture) { + if (!this.observers) this.observers = []; + if (element.addEventListener) { + this.observers.push([element, name, observer, useCapture]); + element.addEventListener(name, observer, useCapture); + } else if (element.attachEvent) { + this.observers.push([element, name, observer, useCapture]); + element.attachEvent('on' + name, observer); + } + }, + + unloadCache: function() { + if (!Event.observers) return; + for (var i = 0, length = Event.observers.length; i < length; i++) { + Event.stopObserving.apply(this, Event.observers[i]); + Event.observers[i][0] = null; + } + Event.observers = false; + }, + + observe: function(element, name, observer, useCapture) { + element = $(element); + useCapture = useCapture || false; + + if (name == 'keypress' && + (navigator.appVersion.match(/Konqueror|Safari|KHTML/) + || element.attachEvent)) + name = 'keydown'; + + Event._observeAndCache(element, name, observer, useCapture); + }, + + stopObserving: function(element, name, observer, useCapture) { + element = $(element); + useCapture = useCapture || false; + + if (name == 'keypress' && + (navigator.appVersion.match(/Konqueror|Safari|KHTML/) + || element.detachEvent)) + name = 'keydown'; + + if (element.removeEventListener) { + element.removeEventListener(name, observer, useCapture); + } else if (element.detachEvent) { + try { + element.detachEvent('on' + name, observer); + } catch (e) {} + } + } +}); + +/* prevent memory leaks in IE */ +if (navigator.appVersion.match(/\bMSIE\b/)) + Event.observe(window, 'unload', Event.unloadCache, false); +var Position = { + // set to true if needed, warning: firefox performance problems + // NOT neeeded for page scrolling, only if draggable contained in + // scrollable elements + includeScrollOffsets: false, + + // must be called before calling withinIncludingScrolloffset, every time the + // page is scrolled + prepare: function() { + this.deltaX = window.pageXOffset + || document.documentElement.scrollLeft + || document.body.scrollLeft + || 0; + this.deltaY = window.pageYOffset + || document.documentElement.scrollTop + || document.body.scrollTop + || 0; + }, + + realOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return [valueL, valueT]; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return [valueL, valueT]; + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if(element.tagName=='BODY') break; + var p = Element.getStyle(element, 'position'); + if (p == 'relative' || p == 'absolute') break; + } + } while (element); + return [valueL, valueT]; + }, + + offsetParent: function(element) { + if (element.offsetParent) return element.offsetParent; + if (element == document.body) return element; + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return element; + + return document.body; + }, + + // caches x/y coordinate pair to use with overlap + within: function(element, x, y) { + if (this.includeScrollOffsets) + return this.withinIncludingScrolloffsets(element, x, y); + this.xcomp = x; + this.ycomp = y; + this.offset = this.cumulativeOffset(element); + + return (y >= this.offset[1] && + y < this.offset[1] + element.offsetHeight && + x >= this.offset[0] && + x < this.offset[0] + element.offsetWidth); + }, + + withinIncludingScrolloffsets: function(element, x, y) { + var offsetcache = this.realOffset(element); + + this.xcomp = x + offsetcache[0] - this.deltaX; + this.ycomp = y + offsetcache[1] - this.deltaY; + this.offset = this.cumulativeOffset(element); + + return (this.ycomp >= this.offset[1] && + this.ycomp < this.offset[1] + element.offsetHeight && + this.xcomp >= this.offset[0] && + this.xcomp < this.offset[0] + element.offsetWidth); + }, + + // within must be called directly before + overlap: function(mode, element) { + if (!mode) return 0; + if (mode == 'vertical') + return ((this.offset[1] + element.offsetHeight) - this.ycomp) / + element.offsetHeight; + if (mode == 'horizontal') + return ((this.offset[0] + element.offsetWidth) - this.xcomp) / + element.offsetWidth; + }, + + page: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + // Safari fix + if (element.offsetParent==document.body) + if (Element.getStyle(element,'position')=='absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + if (!window.opera || element.tagName=='BODY') { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + + return [valueL, valueT]; + }, + + clone: function(source, target) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || {}) + + // find page position of source + source = $(source); + var p = Position.page(source); + + // find coordinate system to use + target = $(target); + var delta = [0, 0]; + var parent = null; + // delta [0,0] will do fine with position: fixed elements, + // position:absolute needs offsetParent deltas + if (Element.getStyle(target,'position') == 'absolute') { + parent = Position.offsetParent(target); + delta = Position.page(parent); + } + + // correct by body offsets (fixes Safari) + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + // set position + if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if(options.setWidth) target.style.width = source.offsetWidth + 'px'; + if(options.setHeight) target.style.height = source.offsetHeight + 'px'; + }, + + absolutize: function(element) { + element = $(element); + if (element.style.position == 'absolute') return; + Position.prepare(); + + var offsets = Position.positionedOffset(element); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.width = width + 'px'; + element.style.height = height + 'px'; + }, + + relativize: function(element) { + element = $(element); + if (element.style.position == 'relative') return; + Position.prepare(); + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + } +} + +// Safari returns margins on body which is incorrect if the child is absolutely +// positioned. For performance reasons, redefine Position.cumulativeOffset for +// KHTML/WebKit only. +if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) { + Position.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return [valueL, valueT]; + } +} + +Element.addMethods(); \ No newline at end of file diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000..4ab9e89 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file \ No newline at end of file diff --git a/public/stylesheets/scaffold.css b/public/stylesheets/scaffold.css new file mode 100644 index 0000000..8f239a3 --- /dev/null +++ b/public/stylesheets/scaffold.css @@ -0,0 +1,74 @@ +body { background-color: #fff; color: #333; } + +body, p, ol, ul, td { + font-family: verdana, arial, helvetica, sans-serif; + font-size: 13px; + line-height: 18px; +} + +pre { + background-color: #eee; + padding: 10px; + font-size: 11px; +} + +a { color: #000; } +a:visited { color: #666; } +a:hover { color: #fff; background-color:#000; } + +.fieldWithErrors { + padding: 2px; + background-color: red; + display: table; +} + +#errorExplanation { + width: 400px; + border: 2px solid red; + padding: 7px; + padding-bottom: 12px; + margin-bottom: 20px; + background-color: #f0f0f0; +} + +#errorExplanation h2 { + text-align: left; + font-weight: bold; + padding: 5px 5px 5px 15px; + font-size: 12px; + margin: -7px; + background-color: #c00; + color: #fff; +} + +#errorExplanation p { + color: #333; + margin-bottom: 0; + padding: 5px; +} + +#errorExplanation ul li { + font-size: 12px; + list-style: square; +} + +div.uploadStatus { + margin: 5px; +} + +div.progressBar { + margin: 5px; +} + +div.progressBar div.border { + background-color: #fff; + border: 1px solid grey; + width: 100%; +} + +div.progressBar div.background { + background-color: #333; + height: 18px; + width: 0%; +} + diff --git a/script/about b/script/about new file mode 100755 index 0000000..7b07d46 --- /dev/null +++ b/script/about @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/about' \ No newline at end of file diff --git a/script/breakpointer b/script/breakpointer new file mode 100755 index 0000000..64af76e --- /dev/null +++ b/script/breakpointer @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/breakpointer' \ No newline at end of file diff --git a/script/console b/script/console new file mode 100755 index 0000000..42f28f7 --- /dev/null +++ b/script/console @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/console' \ No newline at end of file diff --git a/script/destroy b/script/destroy new file mode 100755 index 0000000..fa0e6fc --- /dev/null +++ b/script/destroy @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/destroy' \ No newline at end of file diff --git a/script/generate b/script/generate new file mode 100755 index 0000000..ef976e0 --- /dev/null +++ b/script/generate @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/generate' \ No newline at end of file diff --git a/script/performance/benchmarker b/script/performance/benchmarker new file mode 100755 index 0000000..c842d35 --- /dev/null +++ b/script/performance/benchmarker @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/performance/benchmarker' diff --git a/script/performance/profiler b/script/performance/profiler new file mode 100755 index 0000000..d855ac8 --- /dev/null +++ b/script/performance/profiler @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/performance/profiler' diff --git a/script/plugin b/script/plugin new file mode 100755 index 0000000..26ca64c --- /dev/null +++ b/script/plugin @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/plugin' \ No newline at end of file diff --git a/script/process/inspector b/script/process/inspector new file mode 100755 index 0000000..bf25ad8 --- /dev/null +++ b/script/process/inspector @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/process/inspector' diff --git a/script/process/reaper b/script/process/reaper new file mode 100755 index 0000000..c77f045 --- /dev/null +++ b/script/process/reaper @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/process/reaper' diff --git a/script/process/spawner b/script/process/spawner new file mode 100755 index 0000000..7118f39 --- /dev/null +++ b/script/process/spawner @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/process/spawner' diff --git a/script/runner b/script/runner new file mode 100755 index 0000000..ccc30f9 --- /dev/null +++ b/script/runner @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/runner' \ No newline at end of file diff --git a/script/server b/script/server new file mode 100755 index 0000000..dfabcb8 --- /dev/null +++ b/script/server @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/server' \ No newline at end of file diff --git a/test/fixtures/articles.yml b/test/fixtures/articles.yml new file mode 100644 index 0000000..b49c4eb --- /dev/null +++ b/test/fixtures/articles.yml @@ -0,0 +1,5 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html +one: + id: 1 +two: + id: 2 diff --git a/test/functional/read_controller_test.rb b/test/functional/read_controller_test.rb new file mode 100644 index 0000000..222db99 --- /dev/null +++ b/test/functional/read_controller_test.rb @@ -0,0 +1,18 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'read_controller' + +# Re-raise errors caught by the controller. +class ReadController; def rescue_action(e) raise e end; end + +class ReadControllerTest < Test::Unit::TestCase + def setup + @controller = ReadController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..a299c7f --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,28 @@ +ENV["RAILS_ENV"] = "test" +require File.expand_path(File.dirname(__FILE__) + "/../config/environment") +require 'test_help' + +class Test::Unit::TestCase + # Transactional fixtures accelerate your tests by wrapping each test method + # in a transaction that's rolled back on completion. This ensures that the + # test database remains unchanged so your fixtures don't have to be reloaded + # between every test method. Fewer database queries means faster tests. + # + # Read Mike Clark's excellent walkthrough at + # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting + # + # Every Active Record database supports transactions except MyISAM tables + # in MySQL. Turn off transactional fixtures in this case; however, if you + # don't care one way or the other, switching from MyISAM to InnoDB tables + # is recommended. + self.use_transactional_fixtures = true + + # Instantiated fixtures are slow, but give you @david where otherwise you + # would need people(:david). If you don't want to migrate your existing + # test cases which use the @david style and don't mind the speed hit (each + # instantiated fixtures translates to a database query per test method), + # then set this back to true. + self.use_instantiated_fixtures = false + + # Add more helper methods to be used by all tests here... +end diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb new file mode 100644 index 0000000..f0bda8b --- /dev/null +++ b/test/unit/article_test.rb @@ -0,0 +1,23 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class ArticleTest < Test::Unit::TestCase + fixtures :articles + + # Replace this with your real tests. + def test_truth + assert true + end + + def test_clean_results + article1 = Article.create!(:title=> "a", :uri=>"http://www.example.com/1") + article2 = Article.create!(:title=> "b", :uri=>"http://www.exampel.com/2") + identical_results = [ ["Winter Olympic", article1] , ["Winter Olympic", article2] ] + cleaned_results = Article.clean_results(identical_results) + assert identical_results.size == 2, "Wrong number of original items" + assert cleaned_results.size == 1, "Wrong number of final items" + containing_results = [ ["Winter Olympic Games", article1] , ["Winter Olympic", article2] ] + cleaned_results = Article.clean_results(containing_results) + assert containing_results.size == 2, "Wrong number of original items" + assert cleaned_results.size == 1, "Wrong number of final items" + end +end
bwong/BalloonChallenge
a2d7fef4ad002febc27e6ddee9d9706147e7c4a1
added player highscore comparison, and options save action pops to main window
diff --git a/BalloonChallenge.xcodeproj/bwong.mode1v3 b/BalloonChallenge.xcodeproj/bwong.mode1v3 index 2ecf0f8..1d47b50 100644 --- a/BalloonChallenge.xcodeproj/bwong.mode1v3 +++ b/BalloonChallenge.xcodeproj/bwong.mode1v3 @@ -1,1373 +1,1400 @@ <?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>ActivePerspectiveName</key> <string>Project</string> <key>AllowedModules</key> <array> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Name</key> <string>Groups and Files Outline View</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Name</key> <string>Editor</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCTaskListModule</string> <key>Name</key> <string>Task List</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCDetailModule</string> <key>Name</key> <string>File and Smart Group Detail Viewer</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXBuildResultsModule</string> <key>Name</key> <string>Detailed Build Results Viewer</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXProjectFindModule</string> <key>Name</key> <string>Project Batch Find Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCProjectFormatConflictsModule</string> <key>Name</key> <string>Project Format Conflicts List</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXBookmarksModule</string> <key>Name</key> <string>Bookmarks Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXClassBrowserModule</string> <key>Name</key> <string>Class Browser</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXCVSModule</string> <key>Name</key> <string>Source Code Control Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXDebugBreakpointsModule</string> <key>Name</key> <string>Debug Breakpoints Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCDockableInspector</string> <key>Name</key> <string>Inspector</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXOpenQuicklyModule</string> <key>Name</key> <string>Open Quickly Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXDebugSessionModule</string> <key>Name</key> <string>Debugger</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXDebugCLIModule</string> <key>Name</key> <string>Debug Console</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCSnapshotModule</string> <key>Name</key> <string>Snapshots Tool</string> </dict> </array> <key>BundlePath</key> <string>/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources</string> <key>Description</key> <string>DefaultDescriptionKey</string> <key>DockingSystemVisible</key> <false/> <key>Extension</key> <string>mode1v3</string> <key>FavBarConfig</key> <dict> <key>PBXProjectModuleGUID</key> <string>1D6E99AE111D83EB00661416</string> <key>XCBarModuleItemNames</key> <dict/> <key>XCBarModuleItems</key> <array/> </dict> <key>FirstTimeWindowDisplayed</key> <false/> <key>Identifier</key> <string>com.apple.perspectives.project.mode1v3</string> <key>MajorVersion</key> <integer>33</integer> <key>MinorVersion</key> <integer>0</integer> <key>Name</key> <string>Default</string> <key>Notifications</key> <array/> <key>OpenEditors</key> <array/> <key>PerspectiveWidths</key> <array> <integer>-1</integer> <integer>-1</integer> </array> <key>Perspectives</key> <array> <dict> <key>ChosenToolbarItems</key> <array> <string>active-combo-popup</string> <string>action</string> <string>NSToolbarFlexibleSpaceItem</string> <string>debugger-enable-breakpoints</string> <string>build-and-go</string> <string>com.apple.ide.PBXToolbarStopButton</string> <string>get-info</string> <string>NSToolbarFlexibleSpaceItem</string> <string>com.apple.pbx.toolbar.searchfield</string> </array> <key>ControllerClassBaseName</key> <string></string> <key>IconName</key> <string>WindowOfProjectWithEditor</string> <key>Identifier</key> <string>perspective.project</string> <key>IsVertical</key> <false/> <key>Layout</key> <array> <dict> <key>BecomeActive</key> <true/> <key>ContentConfiguration</key> <dict> <key>PBXBottomSmartGroupGIDs</key> <array> <string>1C37FBAC04509CD000000102</string> <string>1C37FAAC04509CD000000102</string> <string>1C37FABC05509CD000000102</string> <string>1C37FABC05539CD112110102</string> <string>E2644B35053B69B200211256</string> <string>1C37FABC04509CD000100104</string> <string>1CC0EA4004350EF90044410B</string> <string>1CC0EA4004350EF90041110B</string> </array> <key>PBXProjectModuleGUID</key> <string>1CE0B1FE06471DED0097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Files</string> <key>PBXProjectStructureProvided</key> <string>yes</string> <key>PBXSmartGroupTreeModuleColumnData</key> <dict> <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> <array> <real>186</real> </array> <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> <array> <string>MainColumn</string> </array> </dict> <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> <dict> <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> <array> <string>29B97314FDCFA39411CA2CEA</string> <string>080E96DDFE201D6D7F000001</string> <string>29B97317FDCFA39411CA2CEA</string> <string>1C37FABC05509CD000000102</string> </array> <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> <array> <array> - <integer>5</integer> + <integer>23</integer> <integer>1</integer> <integer>0</integer> </array> </array> <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> - <string>{{0, 0}, {186, 445}}</string> + <string>{{0, 95}, {186, 445}}</string> </dict> <key>PBXTopSmartGroupGIDs</key> <array/> <key>XCIncludePerspectivesSwitch</key> <true/> <key>XCSharingToken</key> <string>com.apple.Xcode.GFSharingToken</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {203, 463}}</string> <key>GroupTreeTableConfiguration</key> <array> <string>MainColumn</string> <real>186</real> </array> <key>RubberWindowFrame</key> <string>267 211 788 504 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Proportion</key> <string>203pt</string> </dict> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CE0B20306471E060097A5F4</string> <key>PBXProjectModuleLabel</key> - <string>BalloonChallengeViewController.m</string> + <string>BalloonChallengeAppDelegate.m</string> <key>PBXSplitModuleInNavigatorKey</key> <dict> <key>Split0</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CE0B20406471E060097A5F4</string> <key>PBXProjectModuleLabel</key> - <string>BalloonChallengeViewController.m</string> + <string>BalloonChallengeAppDelegate.m</string> <key>_historyCapacity</key> <integer>0</integer> <key>bookmark</key> - <string>1D3A6784112292F700C55F47</string> + <string>1DA8DD1D113B575E00058042</string> <key>history</key> <array> <string>1D8874B511228F3900700392</string> <string>1D8874B611228F3900700392</string> <string>1D8874B711228F3900700392</string> <string>1D8874B811228F3900700392</string> <string>1D8874BA11228F3900700392</string> + <string>1DA8DD1C113B575E00058042</string> </array> </dict> <key>SplitCount</key> <string>1</string> </dict> <key>StatusBarVisibility</key> <true/> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> - <string>{{0, 0}, {580, 260}}</string> + <string>{{0, 0}, {580, 251}}</string> <key>RubberWindowFrame</key> <string>267 211 788 504 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> - <string>260pt</string> + <string>251pt</string> </dict> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CE0B20506471E060097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Detail</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> - <string>{{0, 265}, {580, 198}}</string> + <string>{{0, 256}, {580, 207}}</string> <key>RubberWindowFrame</key> <string>267 211 788 504 0 0 1280 778 </string> </dict> <key>Module</key> <string>XCDetailModule</string> <key>Proportion</key> - <string>198pt</string> + <string>207pt</string> </dict> </array> <key>Proportion</key> <string>580pt</string> </dict> </array> <key>Name</key> <string>Project</string> <key>ServiceClasses</key> <array> <string>XCModuleDock</string> <string>PBXSmartGroupTreeModule</string> <string>XCModuleDock</string> <string>PBXNavigatorGroup</string> <string>XCDetailModule</string> </array> <key>TableOfContents</key> <array> - <string>1D3A6785112292F700C55F47</string> + <string>1DA8DD1E113B575E00058042</string> <string>1CE0B1FE06471DED0097A5F4</string> - <string>1D3A6786112292F700C55F47</string> + <string>1DA8DD1F113B575E00058042</string> <string>1CE0B20306471E060097A5F4</string> <string>1CE0B20506471E060097A5F4</string> </array> <key>ToolbarConfigUserDefaultsMinorVersion</key> <string>2</string> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.defaultV3</string> </dict> <dict> <key>ControllerClassBaseName</key> <string></string> <key>IconName</key> <string>WindowOfProject</string> <key>Identifier</key> <string>perspective.morph</string> <key>IsVertical</key> <integer>0</integer> <key>Layout</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXBottomSmartGroupGIDs</key> <array> <string>1C37FBAC04509CD000000102</string> <string>1C37FAAC04509CD000000102</string> <string>1C08E77C0454961000C914BD</string> <string>1C37FABC05509CD000000102</string> <string>1C37FABC05539CD112110102</string> <string>E2644B35053B69B200211256</string> <string>1C37FABC04509CD000100104</string> <string>1CC0EA4004350EF90044410B</string> <string>1CC0EA4004350EF90041110B</string> </array> <key>PBXProjectModuleGUID</key> <string>11E0B1FE06471DED0097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Files</string> <key>PBXProjectStructureProvided</key> <string>yes</string> <key>PBXSmartGroupTreeModuleColumnData</key> <dict> <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> <array> <real>186</real> </array> <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> <array> <string>MainColumn</string> </array> </dict> <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> <dict> <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> <array> <string>29B97314FDCFA39411CA2CEA</string> <string>1C37FABC05509CD000000102</string> </array> <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> <array> <array> <integer>0</integer> </array> </array> <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> <string>{{0, 0}, {186, 337}}</string> </dict> <key>PBXTopSmartGroupGIDs</key> <array/> <key>XCIncludePerspectivesSwitch</key> <integer>1</integer> <key>XCSharingToken</key> <string>com.apple.Xcode.GFSharingToken</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {203, 355}}</string> <key>GroupTreeTableConfiguration</key> <array> <string>MainColumn</string> <real>186</real> </array> <key>RubberWindowFrame</key> <string>373 269 690 397 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Morph</string> <key>PreferredWidth</key> <integer>300</integer> <key>ServiceClasses</key> <array> <string>XCModuleDock</string> <string>PBXSmartGroupTreeModule</string> </array> <key>TableOfContents</key> <array> <string>11E0B1FE06471DED0097A5F4</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.default.shortV3</string> </dict> </array> <key>PerspectivesBarVisible</key> <false/> <key>ShelfIsVisible</key> <false/> <key>SourceDescription</key> <string>file at '/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources/XCPerspectivesSpecificationMode1.xcperspec'</string> <key>StatusbarIsVisible</key> <true/> <key>TimeStamp</key> <real>0.0</real> <key>ToolbarConfigUserDefaultsMinorVersion</key> <string>2</string> <key>ToolbarDisplayMode</key> <integer>1</integer> <key>ToolbarIsVisible</key> <true/> <key>ToolbarSizeMode</key> <integer>1</integer> <key>Type</key> <string>Perspectives</string> <key>UpdateMessage</key> <string>The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'?</string> <key>WindowJustification</key> <integer>5</integer> <key>WindowOrderList</key> <array> + <string>1C78EAAD065D492600B07095</string> + <string>1CD10A99069EF8BA00B06720</string> <string>1D6E99AF111D83EB00661416</string> <string>/Users/bwong/Documents/COEN296/BalloonChallenge/BalloonChallenge.xcodeproj</string> </array> <key>WindowString</key> <string>267 211 788 504 0 0 1280 778 </string> <key>WindowToolsV3</key> <array> <dict> <key>FirstTimeWindowDisplayed</key> <false/> <key>Identifier</key> <string>windowTool.build</string> <key>IsVertical</key> <true/> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD0528F0623707200166675</string> <key>PBXProjectModuleLabel</key> <string></string> <key>StatusBarVisibility</key> <true/> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {500, 218}}</string> <key>RubberWindowFrame</key> <string>288 192 500 500 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>218pt</string> </dict> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>XCMainBuildResultsModuleGUID</string> <key>PBXProjectModuleLabel</key> <string>Build Results</string> <key>XCBuildResultsTrigger_Collapse</key> <integer>1021</integer> <key>XCBuildResultsTrigger_Open</key> <integer>1011</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 223}, {500, 236}}</string> <key>RubberWindowFrame</key> <string>288 192 500 500 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXBuildResultsModule</string> <key>Proportion</key> <string>236pt</string> </dict> </array> <key>Proportion</key> <string>459pt</string> </dict> </array> <key>Name</key> <string>Build Results</string> <key>ServiceClasses</key> <array> <string>PBXBuildResultsModule</string> </array> <key>StatusbarIsVisible</key> <true/> <key>TableOfContents</key> <array> <string>1D6E99AF111D83EB00661416</string> - <string>1D3A6787112292F700C55F47</string> + <string>1DA8DD20113B575E00058042</string> <string>1CD0528F0623707200166675</string> <string>XCMainBuildResultsModuleGUID</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.buildV3</string> <key>WindowContentMinSize</key> <string>486 300</string> <key>WindowString</key> <string>288 192 500 500 0 0 1280 778 </string> <key>WindowToolGUID</key> <string>1D6E99AF111D83EB00661416</string> <key>WindowToolIsVisible</key> <false/> </dict> <dict> + <key>FirstTimeWindowDisplayed</key> + <false/> <key>Identifier</key> <string>windowTool.debugger</string> + <key>IsVertical</key> + <true/> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>Debugger</key> <dict> <key>HorizontalSplitView</key> <dict> <key>_collapsingFrameDimension</key> <real>0.0</real> <key>_indexOfCollapsedView</key> <integer>0</integer> <key>_percentageOfCollapsedView</key> <real>0.0</real> <key>isCollapsed</key> <string>yes</string> <key>sizes</key> <array> - <string>{{0, 0}, {317, 164}}</string> - <string>{{317, 0}, {377, 164}}</string> + <string>{{0, 0}, {316, 185}}</string> + <string>{{316, 0}, {378, 185}}</string> </array> </dict> <key>VerticalSplitView</key> <dict> <key>_collapsingFrameDimension</key> <real>0.0</real> <key>_indexOfCollapsedView</key> <integer>0</integer> <key>_percentageOfCollapsedView</key> <real>0.0</real> <key>isCollapsed</key> <string>yes</string> <key>sizes</key> <array> - <string>{{0, 0}, {694, 164}}</string> - <string>{{0, 164}, {694, 216}}</string> + <string>{{0, 0}, {694, 185}}</string> + <string>{{0, 185}, {694, 196}}</string> </array> </dict> </dict> <key>LauncherConfigVersion</key> <string>8</string> <key>PBXProjectModuleGUID</key> <string>1C162984064C10D400B95A72</string> <key>PBXProjectModuleLabel</key> <string>Debug - GLUTExamples (Underwater)</string> </dict> <key>GeometryConfiguration</key> <dict> - <key>DebugConsoleDrawerSize</key> - <string>{100, 120}</string> <key>DebugConsoleVisible</key> <string>None</string> <key>DebugConsoleWindowFrame</key> <string>{{200, 200}, {500, 300}}</string> <key>DebugSTDIOWindowFrame</key> <string>{{200, 200}, {500, 300}}</string> <key>Frame</key> - <string>{{0, 0}, {694, 380}}</string> + <string>{{0, 0}, {694, 381}}</string> + <key>PBXDebugSessionStackFrameViewKey</key> + <dict> + <key>DebugVariablesTableConfiguration</key> + <array> + <string>Name</string> + <real>120</real> + <string>Value</string> + <real>85</real> + <string>Summary</string> + <real>148</real> + </array> + <key>Frame</key> + <string>{{316, 0}, {378, 185}}</string> + <key>RubberWindowFrame</key> + <string>288 270 694 422 0 0 1280 778 </string> + </dict> <key>RubberWindowFrame</key> - <string>321 238 694 422 0 0 1440 878 </string> + <string>288 270 694 422 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXDebugSessionModule</string> <key>Proportion</key> - <string>100%</string> + <string>381pt</string> </dict> </array> <key>Proportion</key> - <string>100%</string> + <string>381pt</string> </dict> </array> <key>Name</key> <string>Debugger</string> <key>ServiceClasses</key> <array> <string>PBXDebugSessionModule</string> </array> <key>StatusbarIsVisible</key> - <integer>1</integer> + <true/> <key>TableOfContents</key> <array> <string>1CD10A99069EF8BA00B06720</string> - <string>1C0AD2AB069F1E9B00FABCE6</string> + <string>1DA8DD21113B575E00058042</string> <string>1C162984064C10D400B95A72</string> - <string>1C0AD2AC069F1E9B00FABCE6</string> + <string>1DA8DD22113B575E00058042</string> + <string>1DA8DD23113B575E00058042</string> + <string>1DA8DD24113B575E00058042</string> + <string>1DA8DD25113B575E00058042</string> + <string>1DA8DD26113B575E00058042</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.debugV3</string> <key>WindowString</key> - <string>321 238 694 422 0 0 1440 878 </string> + <string>288 270 694 422 0 0 1280 778 </string> <key>WindowToolGUID</key> <string>1CD10A99069EF8BA00B06720</string> <key>WindowToolIsVisible</key> - <integer>0</integer> + <false/> </dict> <dict> <key>Identifier</key> <string>windowTool.find</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CDD528C0622207200134675</string> <key>PBXProjectModuleLabel</key> <string>&lt;No Editor&gt;</string> <key>PBXSplitModuleInNavigatorKey</key> <dict> <key>Split0</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD0528D0623707200166675</string> </dict> <key>SplitCount</key> <string>1</string> </dict> <key>StatusBarVisibility</key> <integer>1</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {781, 167}}</string> <key>RubberWindowFrame</key> <string>62 385 781 470 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>781pt</string> </dict> </array> <key>Proportion</key> <string>50%</string> </dict> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD0528E0623707200166675</string> <key>PBXProjectModuleLabel</key> <string>Project Find</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{8, 0}, {773, 254}}</string> <key>RubberWindowFrame</key> <string>62 385 781 470 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXProjectFindModule</string> <key>Proportion</key> <string>50%</string> </dict> </array> <key>Proportion</key> <string>428pt</string> </dict> </array> <key>Name</key> <string>Project Find</string> <key>ServiceClasses</key> <array> <string>PBXProjectFindModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1C530D57069F1CE1000CFCEE</string> <string>1C530D58069F1CE1000CFCEE</string> <string>1C530D59069F1CE1000CFCEE</string> <string>1CDD528C0622207200134675</string> <string>1C530D5A069F1CE1000CFCEE</string> <string>1CE0B1FE06471DED0097A5F4</string> <string>1CD0528E0623707200166675</string> </array> <key>WindowString</key> <string>62 385 781 470 0 0 1440 878 </string> <key>WindowToolGUID</key> <string>1C530D57069F1CE1000CFCEE</string> <key>WindowToolIsVisible</key> <integer>0</integer> </dict> <dict> <key>Identifier</key> <string>MENUSEPARATOR</string> </dict> <dict> + <key>FirstTimeWindowDisplayed</key> + <false/> <key>Identifier</key> <string>windowTool.debuggerConsole</string> + <key>IsVertical</key> + <true/> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> - <key>BecomeActive</key> - <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1C78EAAC065D492600B07095</string> <key>PBXProjectModuleLabel</key> <string>Debugger Console</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> - <string>{{0, 0}, {650, 250}}</string> + <string>{{0, 0}, {650, 209}}</string> <key>RubberWindowFrame</key> - <string>516 632 650 250 0 0 1680 1027 </string> + <string>288 442 650 250 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXDebugCLIModule</string> <key>Proportion</key> <string>209pt</string> </dict> </array> <key>Proportion</key> <string>209pt</string> </dict> </array> <key>Name</key> <string>Debugger Console</string> <key>ServiceClasses</key> <array> <string>PBXDebugCLIModule</string> </array> <key>StatusbarIsVisible</key> - <integer>1</integer> + <true/> <key>TableOfContents</key> <array> <string>1C78EAAD065D492600B07095</string> - <string>1C78EAAE065D492600B07095</string> + <string>1DA8DD27113B575E00058042</string> <string>1C78EAAC065D492600B07095</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.consoleV3</string> <key>WindowString</key> - <string>650 41 650 250 0 0 1280 1002 </string> + <string>288 442 650 250 0 0 1280 778 </string> <key>WindowToolGUID</key> <string>1C78EAAD065D492600B07095</string> <key>WindowToolIsVisible</key> - <integer>0</integer> + <false/> </dict> <dict> <key>Identifier</key> <string>windowTool.snapshots</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Module</key> <string>XCSnapshotModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Snapshots</string> <key>ServiceClasses</key> <array> <string>XCSnapshotModule</string> </array> <key>StatusbarIsVisible</key> <string>Yes</string> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.snapshots</string> <key>WindowString</key> <string>315 824 300 550 0 0 1440 878 </string> <key>WindowToolIsVisible</key> <string>Yes</string> </dict> <dict> <key>Identifier</key> <string>windowTool.scm</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1C78EAB2065D492600B07095</string> <key>PBXProjectModuleLabel</key> <string>&lt;No Editor&gt;</string> <key>PBXSplitModuleInNavigatorKey</key> <dict> <key>Split0</key> <dict> <key>PBXProjectModuleGUID</key> <string>1C78EAB3065D492600B07095</string> </dict> <key>SplitCount</key> <string>1</string> </dict> <key>StatusBarVisibility</key> <integer>1</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {452, 0}}</string> <key>RubberWindowFrame</key> <string>743 379 452 308 0 0 1280 1002 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>0pt</string> </dict> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD052920623707200166675</string> <key>PBXProjectModuleLabel</key> <string>SCM</string> </dict> <key>GeometryConfiguration</key> <dict> <key>ConsoleFrame</key> <string>{{0, 259}, {452, 0}}</string> <key>Frame</key> <string>{{0, 7}, {452, 259}}</string> <key>RubberWindowFrame</key> <string>743 379 452 308 0 0 1280 1002 </string> <key>TableConfiguration</key> <array> <string>Status</string> <real>30</real> <string>FileName</string> <real>199</real> <string>Path</string> <real>197.0950012207031</real> </array> <key>TableFrame</key> <string>{{0, 0}, {452, 250}}</string> </dict> <key>Module</key> <string>PBXCVSModule</string> <key>Proportion</key> <string>262pt</string> </dict> </array> <key>Proportion</key> <string>266pt</string> </dict> </array> <key>Name</key> <string>SCM</string> <key>ServiceClasses</key> <array> <string>PBXCVSModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1C78EAB4065D492600B07095</string> <string>1C78EAB5065D492600B07095</string> <string>1C78EAB2065D492600B07095</string> <string>1CD052920623707200166675</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.scm</string> <key>WindowString</key> <string>743 379 452 308 0 0 1280 1002 </string> </dict> <dict> <key>Identifier</key> <string>windowTool.breakpoints</string> <key>IsVertical</key> <integer>0</integer> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXBottomSmartGroupGIDs</key> <array> <string>1C77FABC04509CD000000102</string> </array> <key>PBXProjectModuleGUID</key> <string>1CE0B1FE06471DED0097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Files</string> <key>PBXProjectStructureProvided</key> <string>no</string> <key>PBXSmartGroupTreeModuleColumnData</key> <dict> <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> <array> <real>168</real> </array> <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> <array> <string>MainColumn</string> </array> </dict> <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> <dict> <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> <array> <string>1C77FABC04509CD000000102</string> </array> <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> <array> <array> <integer>0</integer> </array> </array> <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> <string>{{0, 0}, {168, 350}}</string> </dict> <key>PBXTopSmartGroupGIDs</key> <array/> <key>XCIncludePerspectivesSwitch</key> <integer>0</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {185, 368}}</string> <key>GroupTreeTableConfiguration</key> <array> <string>MainColumn</string> <real>168</real> </array> <key>RubberWindowFrame</key> <string>315 424 744 409 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Proportion</key> <string>185pt</string> </dict> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CA1AED706398EBD00589147</string> <key>PBXProjectModuleLabel</key> <string>Detail</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{190, 0}, {554, 368}}</string> <key>RubberWindowFrame</key> <string>315 424 744 409 0 0 1440 878 </string> </dict> <key>Module</key> <string>XCDetailModule</string> <key>Proportion</key> <string>554pt</string> </dict> </array> <key>Proportion</key> <string>368pt</string> </dict> </array> <key>MajorVersion</key> <integer>3</integer> <key>MinorVersion</key> <integer>0</integer> <key>Name</key> <string>Breakpoints</string> <key>ServiceClasses</key> <array> <string>PBXSmartGroupTreeModule</string> <string>XCDetailModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1CDDB66807F98D9800BB5817</string> <string>1CDDB66907F98D9800BB5817</string> <string>1CE0B1FE06471DED0097A5F4</string> <string>1CA1AED706398EBD00589147</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.breakpointsV3</string> <key>WindowString</key> <string>315 424 744 409 0 0 1440 878 </string> <key>WindowToolGUID</key> <string>1CDDB66807F98D9800BB5817</string> <key>WindowToolIsVisible</key> <integer>1</integer> </dict> <dict> <key>Identifier</key> <string>windowTool.debugAnimator</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Debug Visualizer</string> <key>ServiceClasses</key> <array> <string>PBXNavigatorGroup</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.debugAnimatorV3</string> <key>WindowString</key> <string>100 100 700 500 0 0 1280 1002 </string> </dict> <dict> <key>Identifier</key> <string>windowTool.bookmarks</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Module</key> <string>PBXBookmarksModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Bookmarks</string> <key>ServiceClasses</key> <array> <string>PBXBookmarksModule</string> </array> <key>StatusbarIsVisible</key> <integer>0</integer> <key>WindowString</key> <string>538 42 401 187 0 0 1280 1002 </string> </dict> <dict> <key>Identifier</key> <string>windowTool.projectFormatConflicts</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Module</key> <string>XCProjectFormatConflictsModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Project Format Conflicts</string> <key>ServiceClasses</key> <array> <string>XCProjectFormatConflictsModule</string> </array> <key>StatusbarIsVisible</key> <integer>0</integer> <key>WindowContentMinSize</key> <string>450 300</string> <key>WindowString</key> <string>50 850 472 307 0 0 1440 877</string> </dict> <dict> <key>Identifier</key> <string>windowTool.classBrowser</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>OptionsSetName</key> <string>Hierarchy, all classes</string> <key>PBXProjectModuleGUID</key> <string>1CA6456E063B45B4001379D8</string> <key>PBXProjectModuleLabel</key> <string>Class Browser - NSObject</string> </dict> <key>GeometryConfiguration</key> <dict> <key>ClassesFrame</key> <string>{{0, 0}, {374, 96}}</string> <key>ClassesTreeTableConfiguration</key> <array> <string>PBXClassNameColumnIdentifier</string> <real>208</real> <string>PBXClassBookColumnIdentifier</string> <real>22</real> </array> <key>Frame</key> <string>{{0, 0}, {630, 331}}</string> <key>MembersFrame</key> <string>{{0, 105}, {374, 395}}</string> <key>MembersTreeTableConfiguration</key> <array> <string>PBXMemberTypeIconColumnIdentifier</string> <real>22</real> <string>PBXMemberNameColumnIdentifier</string> <real>216</real> <string>PBXMemberTypeColumnIdentifier</string> <real>97</real> <string>PBXMemberBookColumnIdentifier</string> <real>22</real> </array> <key>PBXModuleWindowStatusBarHidden2</key> <integer>1</integer> <key>RubberWindowFrame</key> <string>385 179 630 352 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXClassBrowserModule</string> <key>Proportion</key> <string>332pt</string> </dict> </array> <key>Proportion</key> <string>332pt</string> </dict> </array> <key>Name</key> <string>Class Browser</string> <key>ServiceClasses</key> <array> <string>PBXClassBrowserModule</string> </array> <key>StatusbarIsVisible</key> <integer>0</integer> <key>TableOfContents</key> <array> <string>1C0AD2AF069F1E9B00FABCE6</string> <string>1C0AD2B0069F1E9B00FABCE6</string> <string>1CA6456E063B45B4001379D8</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.classbrowser</string> <key>WindowString</key> <string>385 179 630 352 0 0 1440 878 </string> <key>WindowToolGUID</key> <string>1C0AD2AF069F1E9B00FABCE6</string> <key>WindowToolIsVisible</key> <integer>0</integer> </dict> <dict> <key>Identifier</key> <string>windowTool.refactoring</string> <key>IncludeInToolsMenu</key> <integer>0</integer> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{0, 0}, {500, 335}</string> <key>RubberWindowFrame</key> <string>{0, 0}, {500, 335}</string> </dict> <key>Module</key> <string>XCRefactoringModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Refactoring</string> <key>ServiceClasses</key> <array> <string>XCRefactoringModule</string> </array> <key>WindowString</key> <string>200 200 500 356 0 0 1920 1200 </string> </dict> </array> </dict> </plist> diff --git a/BalloonChallenge.xcodeproj/bwong.pbxuser b/BalloonChallenge.xcodeproj/bwong.pbxuser index ea97eb5..16c4973 100644 --- a/BalloonChallenge.xcodeproj/bwong.pbxuser +++ b/BalloonChallenge.xcodeproj/bwong.pbxuser @@ -1,206 +1,182 @@ // !$*UTF8*$! { - 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = { + 0A7E98D6113614A100CD5453 /* BalloonChallengeAppDelegate.m */ = { uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {614, 299}}"; + sepNavIntBoundsRect = "{{0, 0}, {558, 1547}}"; sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 523}"; - }; - }; - 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {519, 390}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 418}"; + sepNavVisRange = "{0, 339}"; }; }; 1D3A6784112292F700C55F47 /* PBXTextBookmark */ = { isa = PBXTextBookmark; - fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; name = "BalloonChallengeViewController.m: 1"; rLen = 0; rLoc = 0; rType = 0; vrLen = 522; vrLoc = 0; }; - 1D3A678A1122975D00C55F47 /* OptionsViewController.h */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {519, 228}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 244}"; - }; - }; - 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {519, 228}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 250}"; - }; - }; 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { activeExec = 0; executables = ( 1D6E99A8111D83E700661416 /* BalloonChallenge */, ); }; 1D6E99A8111D83E700661416 /* BalloonChallenge */ = { isa = PBXExecutable; activeArgIndices = ( ); argumentStrings = ( ); autoAttachOnCrash = 1; breakpointsEnabled = 0; configStateDict = { }; customDataFormattersEnabled = 1; dataTipCustomDataFormattersEnabled = 1; dataTipShowTypeColumn = 1; dataTipSortType = 0; debuggerPlugin = GDBDebugging; disassemblyDisplayState = 0; + dylibVariantSuffix = ""; enableDebugStr = 1; environmentEntries = ( ); executableSystemSymbolLevel = 0; executableUserSymbolLevel = 0; libgmallocEnabled = 0; name = BalloonChallenge; showTypeColumn = 0; sourceDirectories = ( ); }; 1D6E99B1111D83EB00661416 /* Source Control */ = { isa = PBXSourceControlManager; fallbackIsa = XCSourceControlManager; isSCMEnabled = 0; scmConfiguration = { repositoryNamesForRoots = { "" = ""; }; }; }; 1D6E99B2111D83EB00661416 /* Code sense */ = { isa = PBXCodeSenseManager; indexTemplatePath = ""; }; 1D8874B511228F3900700392 /* PBXTextBookmark */ = { isa = PBXTextBookmark; - fRef = 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */; name = "BalloonChallengeAppDelegate.h: 1"; rLen = 0; rLoc = 0; rType = 0; vrLen = 523; vrLoc = 0; }; 1D8874B611228F3900700392 /* PBXTextBookmark */ = { isa = PBXTextBookmark; - fRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; name = "BalloonChallengeAppDelegate.m: 1"; rLen = 0; rLoc = 0; rType = 0; vrLen = 418; vrLoc = 0; }; 1D8874B711228F3900700392 /* PBXTextBookmark */ = { isa = PBXTextBookmark; - fRef = 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */; name = "BalloonChallengeViewController.h: 1"; rLen = 0; rLoc = 0; rType = 0; vrLen = 262; vrLoc = 0; }; 1D8874B811228F3900700392 /* PBXBookmark */ = { isa = PBXBookmark; fRef = 0A24546811214737009A536A /* game_bg.png */; }; 1D8874B911228F3900700392 /* PBXTextBookmark */ = { isa = PBXTextBookmark; - fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; name = "BalloonChallengeViewController.m: 1"; rLen = 0; rLoc = 0; rType = 0; vrLen = 555; vrLoc = 0; }; 1D8874BA11228F3900700392 /* PBXTextBookmark */ = { isa = PBXTextBookmark; - fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; name = "BalloonChallengeViewController.m: 1"; rLen = 0; rLoc = 0; rType = 0; vrLen = 555; vrLoc = 0; }; - 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {519, 237}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 262}"; - }; + 1DA8DD1C113B575E00058042 /* PBXBookmark */ = { + isa = PBXBookmark; + fRef = 0A7E98D6113614A100CD5453 /* BalloonChallengeAppDelegate.m */; }; - 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {712, 806}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 522}"; - }; + 1DA8DD1D113B575E00058042 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 0A7E98D6113614A100CD5453 /* BalloonChallengeAppDelegate.m */; + name = "BalloonChallengeAppDelegate.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 339; + vrLoc = 0; }; 29B97313FDCFA39411CA2CEA /* Project object */ = { activeBuildConfigurationName = Debug; activeExecutable = 1D6E99A8111D83E700661416 /* BalloonChallenge */; activeTarget = 1D6058900D05DD3D006BFB54 /* BalloonChallenge */; addToTargets = ( 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, ); codeSenseManager = 1D6E99B2111D83EB00661416 /* Code sense */; executables = ( 1D6E99A8111D83E700661416 /* BalloonChallenge */, ); perUserDictionary = { PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; PBXFileTableDataSourceColumnWidthsKey = ( 20, 341, 20, 48, 43, 43, 20, ); PBXFileTableDataSourceColumnsKey = ( PBXFileDataSource_FiletypeID, PBXFileDataSource_Filename_ColumnID, PBXFileDataSource_Built_ColumnID, PBXFileDataSource_ObjectSize_ColumnID, PBXFileDataSource_Errors_ColumnID, PBXFileDataSource_Warnings_ColumnID, PBXFileDataSource_Target_ColumnID, ); }; - PBXPerProjectTemplateStateSaveDate = 287478498; - PBXWorkspaceStateSaveDate = 287478498; + PBXPerProjectTemplateStateSaveDate = 289101580; + PBXWorkspaceStateSaveDate = 289101580; }; perUserProjectItems = { - 1D3A6784112292F700C55F47 /* PBXTextBookmark */ = 1D3A6784112292F700C55F47 /* PBXTextBookmark */; + 1D3A6784112292F700C55F47 = 1D3A6784112292F700C55F47 /* PBXTextBookmark */; 1D8874B511228F3900700392 = 1D8874B511228F3900700392 /* PBXTextBookmark */; 1D8874B611228F3900700392 = 1D8874B611228F3900700392 /* PBXTextBookmark */; 1D8874B711228F3900700392 = 1D8874B711228F3900700392 /* PBXTextBookmark */; 1D8874B811228F3900700392 = 1D8874B811228F3900700392 /* PBXBookmark */; 1D8874B911228F3900700392 = 1D8874B911228F3900700392 /* PBXTextBookmark */; 1D8874BA11228F3900700392 = 1D8874BA11228F3900700392 /* PBXTextBookmark */; + 1DA8DD1C113B575E00058042 /* PBXBookmark */ = 1DA8DD1C113B575E00058042 /* PBXBookmark */; + 1DA8DD1D113B575E00058042 /* PBXTextBookmark */ = 1DA8DD1D113B575E00058042 /* PBXTextBookmark */; }; sourceControlManager = 1D6E99B1111D83EB00661416 /* Source Control */; userBuildSettings = { }; }; } diff --git a/BalloonChallenge.xcodeproj/project.pbxproj b/BalloonChallenge.xcodeproj/project.pbxproj index 9d26e04..a0d7062 100755 --- a/BalloonChallenge.xcodeproj/project.pbxproj +++ b/BalloonChallenge.xcodeproj/project.pbxproj @@ -1,331 +1,331 @@ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 45; objects = { /* Begin PBXBuildFile section */ 0A24546911214737009A536A /* game_bg.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A24546811214737009A536A /* game_bg.png */; }; 0A3583761133B7AF0095B62A /* GameView.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A3583751133B7AF0095B62A /* GameView.m */; }; 0A358517113510D10095B62A /* Balloon.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A358516113510D10095B62A /* Balloon.m */; }; 0A49A07211337C5200206894 /* blue_balloon.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A49A07111337C5200206894 /* blue_balloon.png */; }; 0A7DD92811365E3E00392A44 /* BalloonFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7DD92711365E3E00392A44 /* BalloonFactory.m */; }; 0A7E98AA113612C800CD5453 /* HelpViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0A7E989D113612C800CD5453 /* HelpViewController.xib */; }; 0A7E98AB113612C800CD5453 /* HelpViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E989F113612C800CD5453 /* HelpViewController.m */; }; 0A7E98AC113612C800CD5453 /* HighScoresViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E98A0113612C800CD5453 /* HighScoresViewController.m */; }; 0A7E98AD113612C800CD5453 /* HighScoresViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0A7E98A1113612C800CD5453 /* HighScoresViewController.xib */; }; 0A7E98AE113612C800CD5453 /* OptionsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0A7E98A3113612C800CD5453 /* OptionsViewController.xib */; }; 0A7E98AF113612C800CD5453 /* OptionsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E98A5113612C800CD5453 /* OptionsViewController.m */; }; 0A7E98B0113612C800CD5453 /* PlayerDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E98A6113612C800CD5453 /* PlayerDatabase.m */; }; 0A7E98B1113612C800CD5453 /* Player.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E98A8113612C800CD5453 /* Player.m */; }; 0A7E98CE113613DA00CD5453 /* BalloonChallengeViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0A7E98CD113613DA00CD5453 /* BalloonChallengeViewController.xib */; }; 0A7E98D21136146A00CD5453 /* BalloonChallengeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E98D11136146A00CD5453 /* BalloonChallengeViewController.m */; }; 0A7E98D7113614A100CD5453 /* BalloonChallengeAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A7E98D6113614A100CD5453 /* BalloonChallengeAppDelegate.m */; }; 0A7E98DB113614DA00CD5453 /* balloonsBackground.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A7E98DA113614DA00CD5453 /* balloonsBackground.png */; }; 0ABCD217113228A200B62EB0 /* GameViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 0ABCD215113228A200B62EB0 /* GameViewController.m */; }; 0ABCD218113228A200B62EB0 /* GameViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0ABCD216113228A200B62EB0 /* GameViewController.xib */; }; 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; }; 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 28AD733E0D9D9553002E5188 /* MainWindow.xib */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 0A24546811214737009A536A /* game_bg.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = game_bg.png; sourceTree = "<group>"; }; 0A3583741133B7AF0095B62A /* GameView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameView.h; sourceTree = "<group>"; }; 0A3583751133B7AF0095B62A /* GameView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GameView.m; sourceTree = "<group>"; }; 0A358515113510D10095B62A /* Balloon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Balloon.h; sourceTree = "<group>"; }; 0A358516113510D10095B62A /* Balloon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Balloon.m; sourceTree = "<group>"; }; 0A49A07111337C5200206894 /* blue_balloon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = blue_balloon.png; sourceTree = "<group>"; }; 0A7DD92611365E3E00392A44 /* BalloonFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonFactory.h; sourceTree = "<group>"; }; 0A7DD92711365E3E00392A44 /* BalloonFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonFactory.m; sourceTree = "<group>"; }; 0A7E989D113612C800CD5453 /* HelpViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = HelpViewController.xib; sourceTree = "<group>"; }; 0A7E989E113612C800CD5453 /* HelpViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelpViewController.h; sourceTree = "<group>"; }; 0A7E989F113612C800CD5453 /* HelpViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HelpViewController.m; sourceTree = "<group>"; }; 0A7E98A0113612C800CD5453 /* HighScoresViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HighScoresViewController.m; sourceTree = "<group>"; }; 0A7E98A1113612C800CD5453 /* HighScoresViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = HighScoresViewController.xib; path = Classes/HighScoresViewController.xib; sourceTree = "<group>"; }; 0A7E98A2113612C800CD5453 /* HighScoresViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HighScoresViewController.h; sourceTree = "<group>"; }; 0A7E98A3113612C800CD5453 /* OptionsViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = OptionsViewController.xib; path = Classes/OptionsViewController.xib; sourceTree = "<group>"; }; 0A7E98A4113612C800CD5453 /* OptionsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OptionsViewController.h; sourceTree = "<group>"; }; 0A7E98A5113612C800CD5453 /* OptionsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OptionsViewController.m; sourceTree = "<group>"; }; 0A7E98A6113612C800CD5453 /* PlayerDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PlayerDatabase.m; sourceTree = "<group>"; }; 0A7E98A7113612C800CD5453 /* PlayerDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerDatabase.h; sourceTree = "<group>"; }; 0A7E98A8113612C800CD5453 /* Player.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Player.m; sourceTree = "<group>"; }; 0A7E98A9113612C800CD5453 /* Player.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Player.h; sourceTree = "<group>"; }; 0A7E98CD113613DA00CD5453 /* BalloonChallengeViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = BalloonChallengeViewController.xib; sourceTree = "<group>"; }; 0A7E98D01136146A00CD5453 /* BalloonChallengeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeViewController.h; sourceTree = "<group>"; }; 0A7E98D11136146A00CD5453 /* BalloonChallengeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeViewController.m; sourceTree = "<group>"; }; 0A7E98D5113614A100CD5453 /* BalloonChallengeAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeAppDelegate.h; sourceTree = "<group>"; }; 0A7E98D6113614A100CD5453 /* BalloonChallengeAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeAppDelegate.m; sourceTree = "<group>"; }; 0A7E98DA113614DA00CD5453 /* balloonsBackground.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = balloonsBackground.png; sourceTree = "<group>"; }; 0ABCD214113228A200B62EB0 /* GameViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameViewController.h; sourceTree = "<group>"; }; 0ABCD215113228A200B62EB0 /* GameViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GameViewController.m; sourceTree = "<group>"; }; 0ABCD216113228A200B62EB0 /* GameViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = GameViewController.xib; path = Classes/GameViewController.xib; sourceTree = "<group>"; }; 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BalloonChallenge.app; sourceTree = BUILT_PRODUCTS_DIR; }; 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; 28AD733E0D9D9553002E5188 /* MainWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MainWindow.xib; sourceTree = "<group>"; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallenge_Prefix.pch; sourceTree = "<group>"; }; 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "BalloonChallenge-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 080E96DDFE201D6D7F000001 /* Classes */ = { isa = PBXGroup; children = ( 0A7E98D01136146A00CD5453 /* BalloonChallengeViewController.h */, 0A7E98D11136146A00CD5453 /* BalloonChallengeViewController.m */, 0A7E98D5113614A100CD5453 /* BalloonChallengeAppDelegate.h */, 0A7E98D6113614A100CD5453 /* BalloonChallengeAppDelegate.m */, 0A7E989D113612C800CD5453 /* HelpViewController.xib */, 0A7E989E113612C800CD5453 /* HelpViewController.h */, 0A7E989F113612C800CD5453 /* HelpViewController.m */, 0A7E98A0113612C800CD5453 /* HighScoresViewController.m */, 0A7E98A2113612C800CD5453 /* HighScoresViewController.h */, 0A7E98A4113612C800CD5453 /* OptionsViewController.h */, 0A7E98A5113612C800CD5453 /* OptionsViewController.m */, 0A7E98A6113612C800CD5453 /* PlayerDatabase.m */, 0A7E98A7113612C800CD5453 /* PlayerDatabase.h */, 0A7E98A8113612C800CD5453 /* Player.m */, 0A7E98A9113612C800CD5453 /* Player.h */, 0ABCD214113228A200B62EB0 /* GameViewController.h */, 0ABCD215113228A200B62EB0 /* GameViewController.m */, 0A3583741133B7AF0095B62A /* GameView.h */, 0A3583751133B7AF0095B62A /* GameView.m */, - 0A358515113510D10095B62A /* Balloon.h */, 0A7DD92611365E3E00392A44 /* BalloonFactory.h */, 0A7DD92711365E3E00392A44 /* BalloonFactory.m */, + 0A358515113510D10095B62A /* Balloon.h */, 0A358516113510D10095B62A /* Balloon.m */, ); path = Classes; sourceTree = "<group>"; }; 19C28FACFE9D520D11CA2CBB /* Products */ = { isa = PBXGroup; children = ( 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */, ); name = Products; sourceTree = "<group>"; }; 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { isa = PBXGroup; children = ( 080E96DDFE201D6D7F000001 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, 29B97317FDCFA39411CA2CEA /* Resources */, 29B97323FDCFA39411CA2CEA /* Frameworks */, 19C28FACFE9D520D11CA2CBB /* Products */, ); name = CustomTemplate; sourceTree = "<group>"; }; 29B97315FDCFA39411CA2CEA /* Other Sources */ = { isa = PBXGroup; children = ( 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */, 29B97316FDCFA39411CA2CEA /* main.m */, ); name = "Other Sources"; sourceTree = "<group>"; }; 29B97317FDCFA39411CA2CEA /* Resources */ = { isa = PBXGroup; children = ( 0A7E98DA113614DA00CD5453 /* balloonsBackground.png */, 0A7E98A3113612C800CD5453 /* OptionsViewController.xib */, 0A7E98A1113612C800CD5453 /* HighScoresViewController.xib */, 0A49A07111337C5200206894 /* blue_balloon.png */, 0A7E98CD113613DA00CD5453 /* BalloonChallengeViewController.xib */, 0A24546811214737009A536A /* game_bg.png */, 28AD733E0D9D9553002E5188 /* MainWindow.xib */, 0ABCD216113228A200B62EB0 /* GameViewController.xib */, 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */, ); name = Resources; sourceTree = "<group>"; }; 29B97323FDCFA39411CA2CEA /* Frameworks */ = { isa = PBXGroup; children = ( 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, 1D30AB110D05D00D00671497 /* Foundation.framework */, 288765A40DF7441C002DB57D /* CoreGraphics.framework */, ); name = Frameworks; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { isa = PBXNativeTarget; buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */; buildPhases = ( 1D60588D0D05DD3D006BFB54 /* Resources */, 1D60588E0D05DD3D006BFB54 /* Sources */, 1D60588F0D05DD3D006BFB54 /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = BalloonChallenge; productName = BalloonChallenge; productReference = 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */; compatibilityVersion = "Xcode 3.1"; hasScannedForEncodings = 1; mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; projectDirPath = ""; projectRoot = ""; targets = ( 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 1D60588D0D05DD3D006BFB54 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */, 0A24546911214737009A536A /* game_bg.png in Resources */, 0ABCD218113228A200B62EB0 /* GameViewController.xib in Resources */, 0A49A07211337C5200206894 /* blue_balloon.png in Resources */, 0A7E98AA113612C800CD5453 /* HelpViewController.xib in Resources */, 0A7E98AD113612C800CD5453 /* HighScoresViewController.xib in Resources */, 0A7E98AE113612C800CD5453 /* OptionsViewController.xib in Resources */, 0A7E98CE113613DA00CD5453 /* BalloonChallengeViewController.xib in Resources */, 0A7E98DB113614DA00CD5453 /* balloonsBackground.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 1D60588E0D05DD3D006BFB54 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 1D60589B0D05DD56006BFB54 /* main.m in Sources */, 0ABCD217113228A200B62EB0 /* GameViewController.m in Sources */, 0A3583761133B7AF0095B62A /* GameView.m in Sources */, 0A358517113510D10095B62A /* Balloon.m in Sources */, 0A7E98AB113612C800CD5453 /* HelpViewController.m in Sources */, 0A7E98AC113612C800CD5453 /* HighScoresViewController.m in Sources */, 0A7E98AF113612C800CD5453 /* OptionsViewController.m in Sources */, 0A7E98B0113612C800CD5453 /* PlayerDatabase.m in Sources */, 0A7E98B1113612C800CD5453 /* Player.m in Sources */, 0A7E98D21136146A00CD5453 /* BalloonChallengeViewController.m in Sources */, 0A7E98D7113614A100CD5453 /* BalloonChallengeAppDelegate.m in Sources */, 0A7DD92811365E3E00392A44 /* BalloonFactory.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 1D6058940D05DD3E006BFB54 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Debug; }; 1D6058950D05DD3E006BFB54 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Release; }; C01FCF4F08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Debug; }; C01FCF5008A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( 1D6058940D05DD3E006BFB54 /* Debug */, 1D6058950D05DD3E006BFB54 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( C01FCF4F08A954540054247B /* Debug */, C01FCF5008A954540054247B /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; } diff --git a/Classes/OptionsViewController.m b/Classes/OptionsViewController.m index 828a4e0..3c6645f 100644 --- a/Classes/OptionsViewController.m +++ b/Classes/OptionsViewController.m @@ -1,126 +1,128 @@ // // OptionsViewController.m // BalloonChallenge // // Created by Brian Wong on 2/9/10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "OptionsViewController.h" @implementation OptionsViewController @synthesize playerName; @synthesize levelLabel; @synthesize backButton; @synthesize saveButton; @synthesize gameDifficulty; // Go Back to Main Window - (IBAction) backButtonPressed: (id) sender { [self dismissModalViewControllerAnimated:YES]; } // Save Information for Default Player for the Session - (IBAction) saveButtonPressed: (id) sender { // Save Player Info // Our AppDelegate has the master player database object // so to access it, we need to get the delegate. BalloonChallengeAppDelegate *appDelegate = (BalloonChallengeAppDelegate*)[[UIApplication sharedApplication] delegate]; int level = [levelLabel.text intValue]; Player *newPlayer = [[Player alloc] initWithName:playerName.text andDifficulty:gameDifficulty andLevel:level andHighscore:0]; appDelegate.defaultPlayer = newPlayer; [appDelegate.playerDatabaseObj addPlayer:playerName.text withDifficultySettingAt:gameDifficulty andLevelSettingAt:level andHighscoreOf:0]; + + [self dismissModalViewControllerAnimated:YES]; } // Switching Levels - (IBAction) sliderChanged: (id) sender { UISlider *slider = (UISlider *) sender; int levelInt = (int) (slider.value); NSString *newText = [[NSString alloc] initWithFormat:@"%d",levelInt]; levelLabel.text = newText; [newText release]; } // Selecting Difficulty - (IBAction) segmentSelected: (id) sender { if ([sender selectedSegmentIndex] == kDifficultyEasy) { gameDifficulty = kDifficultyEasy; } if ([sender selectedSegmentIndex] == kDifficultyNormal) { gameDifficulty = kDifficultyNormal; } if ([sender selectedSegmentIndex] == kDifficultyHard) { gameDifficulty = kDifficultyHard; } } // Helper function for removing Keyboard from screen - (IBAction)textFieldDoneEditing:(id)sender { [sender resignFirstResponder]; } // Helper function for removing Keyboard from screen - (IBAction)backgroundTap:(id)sender { [playerName resignFirstResponder]; } /* // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization } return self; } */ /* // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } */ /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [playerName release]; [levelLabel release]; [backButton release]; [saveButton release]; [super dealloc]; } @end diff --git a/Classes/Player.h b/Classes/Player.h index 7bcc2b9..826c0c4 100644 --- a/Classes/Player.h +++ b/Classes/Player.h @@ -1,32 +1,39 @@ // // Player.h // BalloonChallenge // // Created by Brian Wong on 2/23/10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface Player : NSObject <NSCoding>{ NSString *name; int difficulty; int level; int highscore; } @property (retain) NSString *name; @property int difficulty; @property int level; @property int highscore; /* Create a new player with the specified information. */ - (id) initWithName: (NSString *) newName andDifficulty: (int) newDifficulty andLevel: (int) newLevel andHighscore: (int) newHighscore; +/* Compare against another player alphabetically based on the player's + name. Performs a case-sensitive comparison. */ +- (NSComparisonResult) compareByName: (Player *) otherPlayer; + +/* Compare against another player based on the highscore. */ +- (NSComparisonResult) compareByHighScore: (Player *) otherPlayer; + - (void) dealloc; @end \ No newline at end of file diff --git a/Classes/Player.m b/Classes/Player.m index ffefab7..f923e4e 100644 --- a/Classes/Player.m +++ b/Classes/Player.m @@ -1,63 +1,76 @@ // // Player.m // BalloonChallenge // // Created by Brian Wong on 2/23/10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "Player.h" @implementation Player @synthesize name; @synthesize difficulty; @synthesize level; @synthesize highscore; // Player encoder needed because we're are storing PlayerDatabase // which is made up of Players - (void) encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject: name forKey:@"name"]; [encoder encodeInt: difficulty forKey:@"difficulty"]; [encoder encodeInt:level forKey:@"level"]; [encoder encodeInt:highscore forKey:@"highscore"]; } // Player decoder needed because we're are storing PlayerDatabase // which is made up of Players - (id) initWithCoder: (NSCoder *) decoder { if ( self = [super init]) { self.name = [decoder decodeObjectForKey:@"name"]; difficulty = [decoder decodeIntForKey:@"difficulty"]; level = [decoder decodeIntForKey:@"level"]; highscore = [decoder decodeIntForKey:@"highscore"]; } return self; } /* Create a new quote with the specified data. */ - (id) initWithName: (NSString *) newName andDifficulty: (int) newDifficulty andLevel: (int) newLevel andHighscore: (int) newHighscore { if (self = [super init]) { self.name = newName; difficulty = newDifficulty; level = newLevel; highscore = newHighscore; } return self; } -// TBA - Comparison of Player Objects +/* Compare against another player alphabetically based on the player's + name. Performs a case-sensitive comparison. */ +- (NSComparisonResult) compareByName: (Player *) otherPlayer { + return [name compare:[otherPlayer name]]; +} + +/* Compare against another player based on the highscore. */ +- (NSComparisonResult) compareByHighScore: (Player *) otherPlayer { + if (highscore < [otherPlayer highscore]) + return NSOrderedAscending; + if (highscore > [otherPlayer highscore]) + return NSOrderedDescending; + return NSOrderedSame; +} - (void) dealloc { [name release]; [super dealloc]; } @end diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree index be9b765..db7ab56 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree index 74ff3c0..340a25f 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree index 94dc790..94cc37c 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree index a2b3246..874e712 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header index 79ba192..0ceefb2 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree index 85d7cd1..9fbb934 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree index b537b30..0e8853e 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control index 552d7ab..cb9e57a 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings index bdbbfd1..bd26109 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree index fb5d14e..26b1b95 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols index 97024c7..c46e353 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols differ diff --git a/build/Debug-iphonesimulator/BalloonChallenge.app/BalloonChallenge b/build/Debug-iphonesimulator/BalloonChallenge.app/BalloonChallenge index bc78350..b06a359 100755 Binary files a/build/Debug-iphonesimulator/BalloonChallenge.app/BalloonChallenge and b/build/Debug-iphonesimulator/BalloonChallenge.app/BalloonChallenge differ
bwong/BalloonChallenge
65128342d722f39fee26dcd68580d0a1b3df6c1e
Checkin in newest stuff
diff --git a/BalloonChallenge.xcodeproj/Kevin.mode1v3 b/BalloonChallenge.xcodeproj/Kevin.mode1v3 new file mode 100644 index 0000000..c6b07b5 --- /dev/null +++ b/BalloonChallenge.xcodeproj/Kevin.mode1v3 @@ -0,0 +1,1408 @@ +<?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>ActivePerspectiveName</key> + <string>Project</string> + <key>AllowedModules</key> + <array> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Name</key> + <string>Groups and Files Outline View</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Name</key> + <string>Editor</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCTaskListModule</string> + <key>Name</key> + <string>Task List</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCDetailModule</string> + <key>Name</key> + <string>File and Smart Group Detail Viewer</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXBuildResultsModule</string> + <key>Name</key> + <string>Detailed Build Results Viewer</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXProjectFindModule</string> + <key>Name</key> + <string>Project Batch Find Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCProjectFormatConflictsModule</string> + <key>Name</key> + <string>Project Format Conflicts List</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXBookmarksModule</string> + <key>Name</key> + <string>Bookmarks Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXClassBrowserModule</string> + <key>Name</key> + <string>Class Browser</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXCVSModule</string> + <key>Name</key> + <string>Source Code Control Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXDebugBreakpointsModule</string> + <key>Name</key> + <string>Debug Breakpoints Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCDockableInspector</string> + <key>Name</key> + <string>Inspector</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXOpenQuicklyModule</string> + <key>Name</key> + <string>Open Quickly Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXDebugSessionModule</string> + <key>Name</key> + <string>Debugger</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXDebugCLIModule</string> + <key>Name</key> + <string>Debug Console</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCSnapshotModule</string> + <key>Name</key> + <string>Snapshots Tool</string> + </dict> + </array> + <key>BundlePath</key> + <string>/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources</string> + <key>Description</key> + <string>DefaultDescriptionKey</string> + <key>DockingSystemVisible</key> + <false/> + <key>Extension</key> + <string>mode1v3</string> + <key>FavBarConfig</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>0A24545D11213BA1009A536A</string> + <key>XCBarModuleItemNames</key> + <dict/> + <key>XCBarModuleItems</key> + <array/> + </dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>com.apple.perspectives.project.mode1v3</string> + <key>MajorVersion</key> + <integer>33</integer> + <key>MinorVersion</key> + <integer>0</integer> + <key>Name</key> + <string>Default</string> + <key>Notifications</key> + <array/> + <key>OpenEditors</key> + <array/> + <key>PerspectiveWidths</key> + <array> + <integer>-1</integer> + <integer>-1</integer> + </array> + <key>Perspectives</key> + <array> + <dict> + <key>ChosenToolbarItems</key> + <array> + <string>active-combo-popup</string> + <string>action</string> + <string>NSToolbarFlexibleSpaceItem</string> + <string>debugger-enable-breakpoints</string> + <string>build-and-go</string> + <string>com.apple.ide.PBXToolbarStopButton</string> + <string>get-info</string> + <string>NSToolbarFlexibleSpaceItem</string> + <string>com.apple.pbx.toolbar.searchfield</string> + </array> + <key>ControllerClassBaseName</key> + <string></string> + <key>IconName</key> + <string>WindowOfProjectWithEditor</string> + <key>Identifier</key> + <string>perspective.project</string> + <key>IsVertical</key> + <false/> + <key>Layout</key> + <array> + <dict> + <key>BecomeActive</key> + <true/> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C37FBAC04509CD000000102</string> + <string>1C37FAAC04509CD000000102</string> + <string>1C37FABC05509CD000000102</string> + <string>1C37FABC05539CD112110102</string> + <string>E2644B35053B69B200211256</string> + <string>1C37FABC04509CD000100104</string> + <string>1CC0EA4004350EF90044410B</string> + <string>1CC0EA4004350EF90041110B</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>1CE0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>yes</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>285</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>29B97314FDCFA39411CA2CEA</string> + <string>080E96DDFE201D6D7F000001</string> + <string>29B97315FDCFA39411CA2CEA</string> + <string>29B97317FDCFA39411CA2CEA</string> + <string>1C37FABC05509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>4</integer> + <integer>1</integer> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {285, 509}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <true/> + <key>XCSharingToken</key> + <string>com.apple.Xcode.GFSharingToken</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {302, 527}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>285</real> + </array> + <key>RubberWindowFrame</key> + <string>109 210 986 568 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>302pt</string> + </dict> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20306471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>BalloonChallengeViewController.h</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20406471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>BalloonChallengeViewController.h</string> + <key>_historyCapacity</key> + <integer>0</integer> + <key>bookmark</key> + <string>0A49A0BA11339A2F00206894</string> + <key>history</key> + <array> + <string>0A24545611213BA1009A536A</string> + <string>0A24545811213BA1009A536A</string> + <string>0ABCD2051132283C00B62EB0</string> + <string>0ABCD21D113228BA00B62EB0</string> + <string>0ABCD21E113228BA00B62EB0</string> + <string>0ABCD21F113228BA00B62EB0</string> + <string>0ABCD23A11322ABD00B62EB0</string> + <string>0A49A0B311339A2F00206894</string> + <string>0A49A0B411339A2F00206894</string> + <string>0A49A0B511339A2F00206894</string> + <string>0A49A0B611339A2F00206894</string> + <string>0A49A0B711339A2F00206894</string> + <string>0A49A0B811339A2F00206894</string> + <string>0A49A0B911339A2F00206894</string> + </array> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <true/> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {679, 316}}</string> + <key>RubberWindowFrame</key> + <string>109 210 986 568 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>316pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20506471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Detail</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 321}, {679, 206}}</string> + <key>RubberWindowFrame</key> + <string>109 210 986 568 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>XCDetailModule</string> + <key>Proportion</key> + <string>206pt</string> + </dict> + </array> + <key>Proportion</key> + <string>679pt</string> + </dict> + </array> + <key>Name</key> + <string>Project</string> + <key>ServiceClasses</key> + <array> + <string>XCModuleDock</string> + <string>PBXSmartGroupTreeModule</string> + <string>XCModuleDock</string> + <string>PBXNavigatorGroup</string> + <string>XCDetailModule</string> + </array> + <key>TableOfContents</key> + <array> + <string>0A49A0BB11339A2F00206894</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>0A49A0BC11339A2F00206894</string> + <string>1CE0B20306471E060097A5F4</string> + <string>1CE0B20506471E060097A5F4</string> + </array> + <key>ToolbarConfigUserDefaultsMinorVersion</key> + <string>2</string> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.defaultV3</string> + </dict> + <dict> + <key>ControllerClassBaseName</key> + <string></string> + <key>IconName</key> + <string>WindowOfProject</string> + <key>Identifier</key> + <string>perspective.morph</string> + <key>IsVertical</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C37FBAC04509CD000000102</string> + <string>1C37FAAC04509CD000000102</string> + <string>1C08E77C0454961000C914BD</string> + <string>1C37FABC05509CD000000102</string> + <string>1C37FABC05539CD112110102</string> + <string>E2644B35053B69B200211256</string> + <string>1C37FABC04509CD000100104</string> + <string>1CC0EA4004350EF90044410B</string> + <string>1CC0EA4004350EF90041110B</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>11E0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>yes</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>186</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>29B97314FDCFA39411CA2CEA</string> + <string>1C37FABC05509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {186, 337}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <integer>1</integer> + <key>XCSharingToken</key> + <string>com.apple.Xcode.GFSharingToken</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {203, 355}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>186</real> + </array> + <key>RubberWindowFrame</key> + <string>373 269 690 397 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Morph</string> + <key>PreferredWidth</key> + <integer>300</integer> + <key>ServiceClasses</key> + <array> + <string>XCModuleDock</string> + <string>PBXSmartGroupTreeModule</string> + </array> + <key>TableOfContents</key> + <array> + <string>11E0B1FE06471DED0097A5F4</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.default.shortV3</string> + </dict> + </array> + <key>PerspectivesBarVisible</key> + <false/> + <key>ShelfIsVisible</key> + <false/> + <key>SourceDescription</key> + <string>file at '/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources/XCPerspectivesSpecificationMode1.xcperspec'</string> + <key>StatusbarIsVisible</key> + <true/> + <key>TimeStamp</key> + <real>0.0</real> + <key>ToolbarConfigUserDefaultsMinorVersion</key> + <string>2</string> + <key>ToolbarDisplayMode</key> + <integer>1</integer> + <key>ToolbarIsVisible</key> + <true/> + <key>ToolbarSizeMode</key> + <integer>1</integer> + <key>Type</key> + <string>Perspectives</string> + <key>UpdateMessage</key> + <string>The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'?</string> + <key>WindowJustification</key> + <integer>5</integer> + <key>WindowOrderList</key> + <array> + <string>1CD10A99069EF8BA00B06720</string> + <string>0A24545E11213BA1009A536A</string> + <string>/Users/Kevin/BalloonChallenge/BalloonChallenge.xcodeproj</string> + </array> + <key>WindowString</key> + <string>109 210 986 568 0 0 1280 778 </string> + <key>WindowToolsV3</key> + <array> + <dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>windowTool.build</string> + <key>IsVertical</key> + <true/> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528F0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string></string> + <key>StatusBarVisibility</key> + <true/> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {500, 218}}</string> + <key>RubberWindowFrame</key> + <string>291 200 500 500 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>218pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>XCMainBuildResultsModuleGUID</string> + <key>PBXProjectModuleLabel</key> + <string>Build Results</string> + <key>XCBuildResultsTrigger_Collapse</key> + <integer>1021</integer> + <key>XCBuildResultsTrigger_Open</key> + <integer>1011</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 223}, {500, 236}}</string> + <key>RubberWindowFrame</key> + <string>291 200 500 500 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXBuildResultsModule</string> + <key>Proportion</key> + <string>236pt</string> + </dict> + </array> + <key>Proportion</key> + <string>459pt</string> + </dict> + </array> + <key>Name</key> + <string>Build Results</string> + <key>ServiceClasses</key> + <array> + <string>PBXBuildResultsModule</string> + </array> + <key>StatusbarIsVisible</key> + <true/> + <key>TableOfContents</key> + <array> + <string>0A24545E11213BA1009A536A</string> + <string>0A49A0BD11339A2F00206894</string> + <string>1CD0528F0623707200166675</string> + <string>XCMainBuildResultsModuleGUID</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.buildV3</string> + <key>WindowContentMinSize</key> + <string>486 300</string> + <key>WindowString</key> + <string>291 200 500 500 0 0 1280 778 </string> + <key>WindowToolGUID</key> + <string>0A24545E11213BA1009A536A</string> + <key>WindowToolIsVisible</key> + <false/> + </dict> + <dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>windowTool.debugger</string> + <key>IsVertical</key> + <true/> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>Debugger</key> + <dict> + <key>HorizontalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {316, 198}}</string> + <string>{{316, 0}, {378, 198}}</string> + </array> + </dict> + <key>VerticalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {694, 198}}</string> + <string>{{0, 198}, {694, 183}}</string> + </array> + </dict> + </dict> + <key>LauncherConfigVersion</key> + <string>8</string> + <key>PBXProjectModuleGUID</key> + <string>1C162984064C10D400B95A72</string> + <key>PBXProjectModuleLabel</key> + <string>Debug - GLUTExamples (Underwater)</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>DebugConsoleVisible</key> + <string>None</string> + <key>DebugConsoleWindowFrame</key> + <string>{{200, 200}, {500, 300}}</string> + <key>DebugSTDIOWindowFrame</key> + <string>{{200, 200}, {500, 300}}</string> + <key>Frame</key> + <string>{{0, 0}, {694, 381}}</string> + <key>PBXDebugSessionStackFrameViewKey</key> + <dict> + <key>DebugVariablesTableConfiguration</key> + <array> + <string>Name</string> + <real>120</real> + <string>Value</string> + <real>85</real> + <string>Summary</string> + <real>148</real> + </array> + <key>Frame</key> + <string>{{316, 0}, {378, 198}}</string> + <key>RubberWindowFrame</key> + <string>291 278 694 422 0 0 1280 778 </string> + </dict> + <key>RubberWindowFrame</key> + <string>291 278 694 422 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXDebugSessionModule</string> + <key>Proportion</key> + <string>381pt</string> + </dict> + </array> + <key>Proportion</key> + <string>381pt</string> + </dict> + </array> + <key>Name</key> + <string>Debugger</string> + <key>ServiceClasses</key> + <array> + <string>PBXDebugSessionModule</string> + </array> + <key>StatusbarIsVisible</key> + <true/> + <key>TableOfContents</key> + <array> + <string>1CD10A99069EF8BA00B06720</string> + <string>0A49A0BE11339A2F00206894</string> + <string>1C162984064C10D400B95A72</string> + <string>0A49A0BF11339A2F00206894</string> + <string>0A49A0C011339A2F00206894</string> + <string>0A49A0C111339A2F00206894</string> + <string>0A49A0C211339A2F00206894</string> + <string>0A49A0C311339A2F00206894</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.debugV3</string> + <key>WindowString</key> + <string>291 278 694 422 0 0 1280 778 </string> + <key>WindowToolGUID</key> + <string>1CD10A99069EF8BA00B06720</string> + <key>WindowToolIsVisible</key> + <false/> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.find</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CDD528C0622207200134675</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528D0623707200166675</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {781, 167}}</string> + <key>RubberWindowFrame</key> + <string>62 385 781 470 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>781pt</string> + </dict> + </array> + <key>Proportion</key> + <string>50%</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528E0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>Project Find</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{8, 0}, {773, 254}}</string> + <key>RubberWindowFrame</key> + <string>62 385 781 470 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXProjectFindModule</string> + <key>Proportion</key> + <string>50%</string> + </dict> + </array> + <key>Proportion</key> + <string>428pt</string> + </dict> + </array> + <key>Name</key> + <string>Project Find</string> + <key>ServiceClasses</key> + <array> + <string>PBXProjectFindModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C530D57069F1CE1000CFCEE</string> + <string>1C530D58069F1CE1000CFCEE</string> + <string>1C530D59069F1CE1000CFCEE</string> + <string>1CDD528C0622207200134675</string> + <string>1C530D5A069F1CE1000CFCEE</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1CD0528E0623707200166675</string> + </array> + <key>WindowString</key> + <string>62 385 781 470 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1C530D57069F1CE1000CFCEE</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>MENUSEPARATOR</string> + </dict> + <dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>windowTool.debuggerConsole</string> + <key>IsVertical</key> + <true/> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAAC065D492600B07095</string> + <key>PBXProjectModuleLabel</key> + <string>Debugger Console</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {650, 209}}</string> + <key>RubberWindowFrame</key> + <string>291 450 650 250 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXDebugCLIModule</string> + <key>Proportion</key> + <string>209pt</string> + </dict> + </array> + <key>Proportion</key> + <string>209pt</string> + </dict> + </array> + <key>Name</key> + <string>Debugger Console</string> + <key>ServiceClasses</key> + <array> + <string>PBXDebugCLIModule</string> + </array> + <key>StatusbarIsVisible</key> + <true/> + <key>TableOfContents</key> + <array> + <string>1C78EAAD065D492600B07095</string> + <string>0ABCD2121132283C00B62EB0</string> + <string>1C78EAAC065D492600B07095</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.consoleV3</string> + <key>WindowString</key> + <string>291 450 650 250 0 0 1280 778 </string> + <key>WindowToolGUID</key> + <string>1C78EAAD065D492600B07095</string> + <key>WindowToolIsVisible</key> + <false/> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.snapshots</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>XCSnapshotModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Snapshots</string> + <key>ServiceClasses</key> + <array> + <string>XCSnapshotModule</string> + </array> + <key>StatusbarIsVisible</key> + <string>Yes</string> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.snapshots</string> + <key>WindowString</key> + <string>315 824 300 550 0 0 1440 878 </string> + <key>WindowToolIsVisible</key> + <string>Yes</string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.scm</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAB2065D492600B07095</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAB3065D492600B07095</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {452, 0}}</string> + <key>RubberWindowFrame</key> + <string>743 379 452 308 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>0pt</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD052920623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>SCM</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>ConsoleFrame</key> + <string>{{0, 259}, {452, 0}}</string> + <key>Frame</key> + <string>{{0, 7}, {452, 259}}</string> + <key>RubberWindowFrame</key> + <string>743 379 452 308 0 0 1280 1002 </string> + <key>TableConfiguration</key> + <array> + <string>Status</string> + <real>30</real> + <string>FileName</string> + <real>199</real> + <string>Path</string> + <real>197.0950012207031</real> + </array> + <key>TableFrame</key> + <string>{{0, 0}, {452, 250}}</string> + </dict> + <key>Module</key> + <string>PBXCVSModule</string> + <key>Proportion</key> + <string>262pt</string> + </dict> + </array> + <key>Proportion</key> + <string>266pt</string> + </dict> + </array> + <key>Name</key> + <string>SCM</string> + <key>ServiceClasses</key> + <array> + <string>PBXCVSModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C78EAB4065D492600B07095</string> + <string>1C78EAB5065D492600B07095</string> + <string>1C78EAB2065D492600B07095</string> + <string>1CD052920623707200166675</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.scm</string> + <key>WindowString</key> + <string>743 379 452 308 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.breakpoints</string> + <key>IsVertical</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C77FABC04509CD000000102</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>1CE0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>no</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>168</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>1C77FABC04509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {168, 350}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <integer>0</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {185, 368}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>168</real> + </array> + <key>RubberWindowFrame</key> + <string>315 424 744 409 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>185pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CA1AED706398EBD00589147</string> + <key>PBXProjectModuleLabel</key> + <string>Detail</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{190, 0}, {554, 368}}</string> + <key>RubberWindowFrame</key> + <string>315 424 744 409 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>XCDetailModule</string> + <key>Proportion</key> + <string>554pt</string> + </dict> + </array> + <key>Proportion</key> + <string>368pt</string> + </dict> + </array> + <key>MajorVersion</key> + <integer>3</integer> + <key>MinorVersion</key> + <integer>0</integer> + <key>Name</key> + <string>Breakpoints</string> + <key>ServiceClasses</key> + <array> + <string>PBXSmartGroupTreeModule</string> + <string>XCDetailModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1CDDB66807F98D9800BB5817</string> + <string>1CDDB66907F98D9800BB5817</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1CA1AED706398EBD00589147</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.breakpointsV3</string> + <key>WindowString</key> + <string>315 424 744 409 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1CDDB66807F98D9800BB5817</string> + <key>WindowToolIsVisible</key> + <integer>1</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debugAnimator</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Debug Visualizer</string> + <key>ServiceClasses</key> + <array> + <string>PBXNavigatorGroup</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.debugAnimatorV3</string> + <key>WindowString</key> + <string>100 100 700 500 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.bookmarks</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>PBXBookmarksModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Bookmarks</string> + <key>ServiceClasses</key> + <array> + <string>PBXBookmarksModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>WindowString</key> + <string>538 42 401 187 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.projectFormatConflicts</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>XCProjectFormatConflictsModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Project Format Conflicts</string> + <key>ServiceClasses</key> + <array> + <string>XCProjectFormatConflictsModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>WindowContentMinSize</key> + <string>450 300</string> + <key>WindowString</key> + <string>50 850 472 307 0 0 1440 877</string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.classBrowser</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>OptionsSetName</key> + <string>Hierarchy, all classes</string> + <key>PBXProjectModuleGUID</key> + <string>1CA6456E063B45B4001379D8</string> + <key>PBXProjectModuleLabel</key> + <string>Class Browser - NSObject</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>ClassesFrame</key> + <string>{{0, 0}, {374, 96}}</string> + <key>ClassesTreeTableConfiguration</key> + <array> + <string>PBXClassNameColumnIdentifier</string> + <real>208</real> + <string>PBXClassBookColumnIdentifier</string> + <real>22</real> + </array> + <key>Frame</key> + <string>{{0, 0}, {630, 331}}</string> + <key>MembersFrame</key> + <string>{{0, 105}, {374, 395}}</string> + <key>MembersTreeTableConfiguration</key> + <array> + <string>PBXMemberTypeIconColumnIdentifier</string> + <real>22</real> + <string>PBXMemberNameColumnIdentifier</string> + <real>216</real> + <string>PBXMemberTypeColumnIdentifier</string> + <real>97</real> + <string>PBXMemberBookColumnIdentifier</string> + <real>22</real> + </array> + <key>PBXModuleWindowStatusBarHidden2</key> + <integer>1</integer> + <key>RubberWindowFrame</key> + <string>385 179 630 352 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXClassBrowserModule</string> + <key>Proportion</key> + <string>332pt</string> + </dict> + </array> + <key>Proportion</key> + <string>332pt</string> + </dict> + </array> + <key>Name</key> + <string>Class Browser</string> + <key>ServiceClasses</key> + <array> + <string>PBXClassBrowserModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>TableOfContents</key> + <array> + <string>1C0AD2AF069F1E9B00FABCE6</string> + <string>1C0AD2B0069F1E9B00FABCE6</string> + <string>1CA6456E063B45B4001379D8</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.classbrowser</string> + <key>WindowString</key> + <string>385 179 630 352 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1C0AD2AF069F1E9B00FABCE6</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.refactoring</string> + <key>IncludeInToolsMenu</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{0, 0}, {500, 335}</string> + <key>RubberWindowFrame</key> + <string>{0, 0}, {500, 335}</string> + </dict> + <key>Module</key> + <string>XCRefactoringModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Refactoring</string> + <key>ServiceClasses</key> + <array> + <string>XCRefactoringModule</string> + </array> + <key>WindowString</key> + <string>200 200 500 356 0 0 1920 1200 </string> + </dict> + </array> +</dict> +</plist> diff --git a/BalloonChallenge.xcodeproj/Kevin.pbxuser b/BalloonChallenge.xcodeproj/Kevin.pbxuser new file mode 100644 index 0000000..6c01fb7 --- /dev/null +++ b/BalloonChallenge.xcodeproj/Kevin.pbxuser @@ -0,0 +1,333 @@ +// !$*UTF8*$! +{ + 0A24544611213AEA009A536A /* BalloonChallenge */ = { + isa = PBXExecutable; + activeArgIndices = ( + ); + argumentStrings = ( + ); + autoAttachOnCrash = 1; + breakpointsEnabled = 0; + configStateDict = { + }; + customDataFormattersEnabled = 1; + dataTipCustomDataFormattersEnabled = 1; + dataTipShowTypeColumn = 1; + dataTipSortType = 0; + debuggerPlugin = GDBDebugging; + disassemblyDisplayState = 0; + dylibVariantSuffix = ""; + enableDebugStr = 1; + environmentEntries = ( + ); + executableSystemSymbolLevel = 0; + executableUserSymbolLevel = 0; + libgmallocEnabled = 0; + name = BalloonChallenge; + showTypeColumn = 0; + sourceDirectories = ( + ); + }; + 0A24544A11213B09009A536A /* Source Control */ = { + isa = PBXSourceControlManager; + fallbackIsa = XCSourceControlManager; + isSCMEnabled = 0; + scmConfiguration = { + repositoryNamesForRoots = { + "" = ""; + }; + }; + }; + 0A24544B11213B09009A536A /* Code sense */ = { + isa = PBXCodeSenseManager; + indexTemplatePath = ""; + }; + 0A24545611213BA1009A536A /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */; + name = "BalloonChallengeAppDelegate.h: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 523; + vrLoc = 0; + }; + 0A24545811213BA1009A536A /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + name = "GameView.h: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 220; + vrLoc = 0; + }; + 0A24546811214737009A536A /* game_bg.png */ = { + uiCtxt = { + sepNavWindowFrame = "{{69, 0}, {959, 778}}"; + }; + }; + 0A49A07111337C5200206894 /* blue_balloon.png */ = { + uiCtxt = { + sepNavWindowFrame = "{{69, 0}, {959, 778}}"; + }; + }; + 0A49A0B311339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; + name = "BalloonChallengeViewController.m: 15"; + rLen = 0; + rLoc = 356; + rType = 0; + vrLen = 701; + vrLoc = 0; + }; + 0A49A0B411339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 0ABCD215113228A200B62EB0 /* GameViewController.m */; + name = "GameViewController.m: 24"; + rLen = 0; + rLoc = 612; + rType = 0; + vrLen = 634; + vrLoc = 608; + }; + 0A49A0B511339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 0ABCD214113228A200B62EB0 /* GameViewController.h */; + name = "GameViewController.h: 9"; + rLen = 0; + rLoc = 178; + rType = 0; + vrLen = 241; + vrLoc = 0; + }; + 0A49A0B611339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */; + name = "BalloonChallenge_Prefix.pch: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 201; + vrLoc = 0; + }; + 0A49A0B711339A2F00206894 /* PBXBookmark */ = { + isa = PBXBookmark; + fRef = 0A49A07111337C5200206894 /* blue_balloon.png */; + }; + 0A49A0B811339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; + name = "BalloonChallengeAppDelegate.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 556; + vrLoc = 0; + }; + 0A49A0B911339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */; + name = "BalloonChallengeViewController.h: 17"; + rLen = 0; + rLoc = 406; + rType = 0; + vrLen = 458; + vrLoc = 0; + }; + 0A49A0BA11339A2F00206894 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */; + name = "BalloonChallengeViewController.h: 17"; + rLen = 0; + rLoc = 406; + rType = 0; + vrLen = 458; + vrLoc = 0; + }; + 0ABCD2051132283C00B62EB0 /* PBXBookmark */ = { + isa = PBXBookmark; + fRef = 0A24546811214737009A536A /* game_bg.png */; + }; + 0ABCD214113228A200B62EB0 /* GameViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {618, 284}}"; + sepNavSelRange = "{178, 0}"; + sepNavVisRange = "{0, 241}"; + }; + }; + 0ABCD215113228A200B62EB0 /* GameViewController.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {1146, 689}}"; + sepNavSelRange = "{612, 0}"; + sepNavVisRange = "{608, 634}"; + }; + }; + 0ABCD21D113228BA00B62EB0 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3A678B1122975D00C55F47 /* OptionsViewController.m */; + name = "OptionsViewController.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 479; + vrLoc = 0; + }; + 0ABCD21E113228BA00B62EB0 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3A678A1122975D00C55F47 /* OptionsViewController.h */; + name = "OptionsViewController.h: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 244; + vrLoc = 0; + }; + 0ABCD21F113228BA00B62EB0 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */; + name = "HighScoresViewController.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 472; + vrLoc = 154; + }; + 0ABCD23A11322ABD00B62EB0 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */; + name = "HighScoresViewController.h: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 250; + vrLoc = 0; + }; + 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {614, 299}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 523}"; + }; + }; + 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {618, 416}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 556}"; + }; + }; + 1D3A678A1122975D00C55F47 /* OptionsViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {420, 221}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 244}"; + }; + }; + 1D3A678B1122975D00C55F47 /* OptionsViewController.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {1146, 702}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 479}"; + }; + }; + 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {420, 221}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 250}"; + }; + }; + 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {1146, 741}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{154, 472}"; + }; + }; + 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { + activeExec = 0; + executables = ( + 0A24544611213AEA009A536A /* BalloonChallenge */, + ); + }; + 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {618, 286}}"; + sepNavSelRange = "{406, 0}"; + sepNavVisRange = "{0, 458}"; + }; + }; + 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {712, 897}}"; + sepNavSelRange = "{356, 0}"; + sepNavVisRange = "{0, 701}"; + }; + }; + 29B97313FDCFA39411CA2CEA /* Project object */ = { + activeBuildConfigurationName = Debug; + activeExecutable = 0A24544611213AEA009A536A /* BalloonChallenge */; + activeTarget = 1D6058900D05DD3D006BFB54 /* BalloonChallenge */; + addToTargets = ( + 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, + ); + codeSenseManager = 0A24544B11213B09009A536A /* Code sense */; + executables = ( + 0A24544611213AEA009A536A /* BalloonChallenge */, + ); + perUserDictionary = { + PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { + PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; + PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; + PBXFileTableDataSourceColumnWidthsKey = ( + 20, + 440, + 20, + 48, + 43, + 43, + 20, + ); + PBXFileTableDataSourceColumnsKey = ( + PBXFileDataSource_FiletypeID, + PBXFileDataSource_Filename_ColumnID, + PBXFileDataSource_Built_ColumnID, + PBXFileDataSource_ObjectSize_ColumnID, + PBXFileDataSource_Errors_ColumnID, + PBXFileDataSource_Warnings_ColumnID, + PBXFileDataSource_Target_ColumnID, + ); + }; + PBXPerProjectTemplateStateSaveDate = 288586340; + PBXWorkspaceStateSaveDate = 288586340; + }; + perUserProjectItems = { + 0A24545611213BA1009A536A /* PBXTextBookmark */ = 0A24545611213BA1009A536A /* PBXTextBookmark */; + 0A24545811213BA1009A536A /* PBXTextBookmark */ = 0A24545811213BA1009A536A /* PBXTextBookmark */; + 0A49A0B311339A2F00206894 /* PBXTextBookmark */ = 0A49A0B311339A2F00206894 /* PBXTextBookmark */; + 0A49A0B411339A2F00206894 /* PBXTextBookmark */ = 0A49A0B411339A2F00206894 /* PBXTextBookmark */; + 0A49A0B511339A2F00206894 /* PBXTextBookmark */ = 0A49A0B511339A2F00206894 /* PBXTextBookmark */; + 0A49A0B611339A2F00206894 /* PBXTextBookmark */ = 0A49A0B611339A2F00206894 /* PBXTextBookmark */; + 0A49A0B711339A2F00206894 /* PBXBookmark */ = 0A49A0B711339A2F00206894 /* PBXBookmark */; + 0A49A0B811339A2F00206894 /* PBXTextBookmark */ = 0A49A0B811339A2F00206894 /* PBXTextBookmark */; + 0A49A0B911339A2F00206894 /* PBXTextBookmark */ = 0A49A0B911339A2F00206894 /* PBXTextBookmark */; + 0A49A0BA11339A2F00206894 /* PBXTextBookmark */ = 0A49A0BA11339A2F00206894 /* PBXTextBookmark */; + 0ABCD2051132283C00B62EB0 /* PBXBookmark */ = 0ABCD2051132283C00B62EB0 /* PBXBookmark */; + 0ABCD21D113228BA00B62EB0 /* PBXTextBookmark */ = 0ABCD21D113228BA00B62EB0 /* PBXTextBookmark */; + 0ABCD21E113228BA00B62EB0 /* PBXTextBookmark */ = 0ABCD21E113228BA00B62EB0 /* PBXTextBookmark */; + 0ABCD21F113228BA00B62EB0 /* PBXTextBookmark */ = 0ABCD21F113228BA00B62EB0 /* PBXTextBookmark */; + 0ABCD23A11322ABD00B62EB0 /* PBXTextBookmark */ = 0ABCD23A11322ABD00B62EB0 /* PBXTextBookmark */; + }; + sourceControlManager = 0A24544A11213B09009A536A /* Source Control */; + userBuildSettings = { + }; + }; + 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {740, 284}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 201}"; + }; + }; +} diff --git a/BalloonChallenge.xcodeproj/project.pbxproj b/BalloonChallenge.xcodeproj/project.pbxproj index 8fda9ce..8585848 100755 --- a/BalloonChallenge.xcodeproj/project.pbxproj +++ b/BalloonChallenge.xcodeproj/project.pbxproj @@ -1,273 +1,287 @@ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 45; objects = { /* Begin PBXBuildFile section */ 0A24546911214737009A536A /* game_bg.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A24546811214737009A536A /* game_bg.png */; }; + 0A49A07211337C5200206894 /* blue_balloon.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A49A07111337C5200206894 /* blue_balloon.png */; }; + 0ABCD217113228A200B62EB0 /* GameViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 0ABCD215113228A200B62EB0 /* GameViewController.m */; }; + 0ABCD218113228A200B62EB0 /* GameViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0ABCD216113228A200B62EB0 /* GameViewController.xib */; }; 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; }; 1D3A678D1122975D00C55F47 /* OptionsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3A678B1122975D00C55F47 /* OptionsViewController.m */; }; 1D3A678E1122975D00C55F47 /* OptionsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1D3A678C1122975D00C55F47 /* OptionsViewController.xib */; }; 1D3A679D112297CA00C55F47 /* HighScoresViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */; }; 1D3A679E112297CA00C55F47 /* HighScoresViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1D3A679C112297CA00C55F47 /* HighScoresViewController.xib */; }; 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; }; 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */; }; 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 28AD733E0D9D9553002E5188 /* MainWindow.xib */; }; 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 0A24546811214737009A536A /* game_bg.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = game_bg.png; sourceTree = "<group>"; }; + 0A49A07111337C5200206894 /* blue_balloon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = blue_balloon.png; sourceTree = "<group>"; }; + 0ABCD214113228A200B62EB0 /* GameViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameViewController.h; sourceTree = "<group>"; }; + 0ABCD215113228A200B62EB0 /* GameViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GameViewController.m; sourceTree = "<group>"; }; + 0ABCD216113228A200B62EB0 /* GameViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = GameViewController.xib; path = Classes/GameViewController.xib; sourceTree = "<group>"; }; 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeAppDelegate.h; sourceTree = "<group>"; }; 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeAppDelegate.m; sourceTree = "<group>"; }; 1D3A678A1122975D00C55F47 /* OptionsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OptionsViewController.h; sourceTree = "<group>"; }; 1D3A678B1122975D00C55F47 /* OptionsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OptionsViewController.m; sourceTree = "<group>"; }; 1D3A678C1122975D00C55F47 /* OptionsViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = OptionsViewController.xib; path = Classes/OptionsViewController.xib; sourceTree = "<group>"; }; 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HighScoresViewController.h; sourceTree = "<group>"; }; 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HighScoresViewController.m; sourceTree = "<group>"; }; 1D3A679C112297CA00C55F47 /* HighScoresViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = HighScoresViewController.xib; path = Classes/HighScoresViewController.xib; sourceTree = "<group>"; }; 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BalloonChallenge.app; sourceTree = BUILT_PRODUCTS_DIR; }; 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = BalloonChallengeViewController.xib; sourceTree = "<group>"; }; 28AD733E0D9D9553002E5188 /* MainWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MainWindow.xib; sourceTree = "<group>"; }; 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeViewController.h; sourceTree = "<group>"; }; 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeViewController.m; sourceTree = "<group>"; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallenge_Prefix.pch; sourceTree = "<group>"; }; 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "BalloonChallenge-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 080E96DDFE201D6D7F000001 /* Classes */ = { isa = PBXGroup; children = ( 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */, 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */, 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */, 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */, 1D3A678A1122975D00C55F47 /* OptionsViewController.h */, 1D3A678B1122975D00C55F47 /* OptionsViewController.m */, 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */, 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */, + 0ABCD214113228A200B62EB0 /* GameViewController.h */, + 0ABCD215113228A200B62EB0 /* GameViewController.m */, ); path = Classes; sourceTree = "<group>"; }; 19C28FACFE9D520D11CA2CBB /* Products */ = { isa = PBXGroup; children = ( 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */, ); name = Products; sourceTree = "<group>"; }; 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { isa = PBXGroup; children = ( 080E96DDFE201D6D7F000001 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, 29B97317FDCFA39411CA2CEA /* Resources */, 29B97323FDCFA39411CA2CEA /* Frameworks */, 19C28FACFE9D520D11CA2CBB /* Products */, ); name = CustomTemplate; sourceTree = "<group>"; }; 29B97315FDCFA39411CA2CEA /* Other Sources */ = { isa = PBXGroup; children = ( 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */, 29B97316FDCFA39411CA2CEA /* main.m */, ); name = "Other Sources"; sourceTree = "<group>"; }; 29B97317FDCFA39411CA2CEA /* Resources */ = { isa = PBXGroup; children = ( + 0A49A07111337C5200206894 /* blue_balloon.png */, 1D3A679C112297CA00C55F47 /* HighScoresViewController.xib */, 0A24546811214737009A536A /* game_bg.png */, 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */, 28AD733E0D9D9553002E5188 /* MainWindow.xib */, + 0ABCD216113228A200B62EB0 /* GameViewController.xib */, 1D3A678C1122975D00C55F47 /* OptionsViewController.xib */, 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */, ); name = Resources; sourceTree = "<group>"; }; 29B97323FDCFA39411CA2CEA /* Frameworks */ = { isa = PBXGroup; children = ( 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, 1D30AB110D05D00D00671497 /* Foundation.framework */, 288765A40DF7441C002DB57D /* CoreGraphics.framework */, ); name = Frameworks; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { isa = PBXNativeTarget; buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */; buildPhases = ( 1D60588D0D05DD3D006BFB54 /* Resources */, 1D60588E0D05DD3D006BFB54 /* Sources */, 1D60588F0D05DD3D006BFB54 /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = BalloonChallenge; productName = BalloonChallenge; productReference = 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */; compatibilityVersion = "Xcode 3.1"; hasScannedForEncodings = 1; mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; projectDirPath = ""; projectRoot = ""; targets = ( 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 1D60588D0D05DD3D006BFB54 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */, 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */, 0A24546911214737009A536A /* game_bg.png in Resources */, 1D3A678E1122975D00C55F47 /* OptionsViewController.xib in Resources */, 1D3A679E112297CA00C55F47 /* HighScoresViewController.xib in Resources */, + 0ABCD218113228A200B62EB0 /* GameViewController.xib in Resources */, + 0A49A07211337C5200206894 /* blue_balloon.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 1D60588E0D05DD3D006BFB54 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 1D60589B0D05DD56006BFB54 /* main.m in Sources */, 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */, 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */, 1D3A678D1122975D00C55F47 /* OptionsViewController.m in Sources */, 1D3A679D112297CA00C55F47 /* HighScoresViewController.m in Sources */, + 0ABCD217113228A200B62EB0 /* GameViewController.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 1D6058940D05DD3E006BFB54 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Debug; }; 1D6058950D05DD3E006BFB54 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Release; }; C01FCF4F08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Debug; }; C01FCF5008A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( 1D6058940D05DD3E006BFB54 /* Debug */, 1D6058950D05DD3E006BFB54 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( C01FCF4F08A954540054247B /* Debug */, C01FCF5008A954540054247B /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; } diff --git a/BalloonChallengeViewController.xib b/BalloonChallengeViewController.xib index 5671341..f84a742 100644 --- a/BalloonChallengeViewController.xib +++ b/BalloonChallengeViewController.xib @@ -1,501 +1,550 @@ <?xml version="1.0" encoding="UTF-8"?> <archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> <data> <int key="IBDocument.SystemTarget">784</int> <string key="IBDocument.SystemVersion">10C540</string> <string key="IBDocument.InterfaceBuilderVersion">740</string> <string key="IBDocument.AppKitVersion">1038.25</string> <string key="IBDocument.HIToolboxVersion">458.00</string> <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> <string key="NS.object.0">62</string> </object> <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> <bool key="EncodedWithXMLCoder">YES</bool> + <integer value="14"/> <integer value="6"/> </object> <object class="NSArray" key="IBDocument.PluginDependencies"> <bool key="EncodedWithXMLCoder">YES</bool> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> </object> <object class="NSMutableDictionary" key="IBDocument.Metadata"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="NSArray" key="dict.sortedKeys" id="0"> <bool key="EncodedWithXMLCoder">YES</bool> </object> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> </object> </object> <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBProxyObject" id="372490531"> <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> </object> <object class="IBProxyObject" id="843779117"> <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> </object> + <object class="IBUIViewController" id="139201391"> + <string key="IBUINibName">GameViewController</string> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> <object class="IBUIView" id="774585933"> <reference key="NSNextResponder"/> <int key="NSvFlags">274</int> <object class="NSMutableArray" key="NSSubviews"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBUIImageView" id="1015927794"> <reference key="NSNextResponder" ref="774585933"/> <int key="NSvFlags">274</int> <string key="NSFrameSize">{320, 460}</string> <reference key="NSSuperview" ref="774585933"/> <bool key="IBUIOpaque">NO</bool> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <int key="IBUIContentMode">4</int> <bool key="IBUIUserInteractionEnabled">NO</bool> <object class="NSCustomResource" key="IBUIImage"> <string key="NSClassName">NSImage</string> <string key="NSResourceName">game_bg.png</string> </object> </object> <object class="IBUIButton" id="879414223"> <reference key="NSNextResponder" ref="774585933"/> <int key="NSvFlags">292</int> <string key="NSFrame">{{103, 150}, {113, 37}}</string> <reference key="NSSuperview" ref="774585933"/> <bool key="IBUIOpaque">NO</bool> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <int key="IBUIContentHorizontalAlignment">0</int> <int key="IBUIContentVerticalAlignment">0</int> <object class="NSFont" key="IBUIFont" id="954580566"> <string key="NSName">Helvetica-Bold</string> <double key="NSSize">15</double> <int key="NSfFlags">16</int> </object> <int key="IBUIButtonType">1</int> <string key="IBUINormalTitle">Play</string> <object class="NSColor" key="IBUIHighlightedTitleColor" id="186910058"> <int key="NSColorSpace">3</int> <bytes key="NSWhite">MQA</bytes> </object> <object class="NSColor" key="IBUINormalTitleColor"> <int key="NSColorSpace">1</int> <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> </object> <object class="NSColor" key="IBUINormalTitleShadowColor" id="399200713"> <int key="NSColorSpace">3</int> <bytes key="NSWhite">MC41AA</bytes> </object> </object> <object class="IBUIButton" id="315950724"> <reference key="NSNextResponder" ref="774585933"/> <int key="NSvFlags">292</int> <string key="NSFrame">{{103, 195}, {113, 37}}</string> <reference key="NSSuperview" ref="774585933"/> <bool key="IBUIOpaque">NO</bool> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <int key="IBUIContentHorizontalAlignment">0</int> <int key="IBUIContentVerticalAlignment">0</int> <reference key="IBUIFont" ref="954580566"/> <int key="IBUIButtonType">1</int> <string key="IBUINormalTitle">Options</string> <reference key="IBUIHighlightedTitleColor" ref="186910058"/> <object class="NSColor" key="IBUINormalTitleColor"> <int key="NSColorSpace">1</int> <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> </object> <reference key="IBUINormalTitleShadowColor" ref="399200713"/> </object> <object class="IBUIButton" id="1039261273"> <reference key="NSNextResponder" ref="774585933"/> <int key="NSvFlags">292</int> <string key="NSFrame">{{103, 285}, {113, 37}}</string> <reference key="NSSuperview" ref="774585933"/> <bool key="IBUIOpaque">NO</bool> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <int key="IBUIContentHorizontalAlignment">0</int> <int key="IBUIContentVerticalAlignment">0</int> <reference key="IBUIFont" ref="954580566"/> <int key="IBUIButtonType">1</int> <string key="IBUINormalTitle">Help</string> <reference key="IBUIHighlightedTitleColor" ref="186910058"/> <object class="NSColor" key="IBUINormalTitleColor"> <int key="NSColorSpace">1</int> <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> </object> <reference key="IBUINormalTitleShadowColor" ref="399200713"/> </object> <object class="IBUIButton" id="578362606"> <reference key="NSNextResponder" ref="774585933"/> <int key="NSvFlags">292</int> <string key="NSFrame">{{103, 240}, {113, 37}}</string> <reference key="NSSuperview" ref="774585933"/> <bool key="IBUIOpaque">NO</bool> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <int key="IBUIContentHorizontalAlignment">0</int> <int key="IBUIContentVerticalAlignment">0</int> <reference key="IBUIFont" ref="954580566"/> <int key="IBUIButtonType">1</int> <string key="IBUINormalTitle">High Scores</string> <reference key="IBUIHighlightedTitleColor" ref="186910058"/> <object class="NSColor" key="IBUINormalTitleColor"> <int key="NSColorSpace">1</int> <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> </object> <reference key="IBUINormalTitleShadowColor" ref="399200713"/> </object> </object> <string key="NSFrameSize">{320, 460}</string> <reference key="NSSuperview"/> <object class="NSColor" key="IBUIBackgroundColor"> <int key="NSColorSpace">3</int> <bytes key="NSWhite">MC43NQA</bytes> <object class="NSColorSpace" key="NSCustomColorSpace"> <int key="NSID">2</int> </object> </object> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> </object> </object> <object class="IBObjectContainer" key="IBDocument.Objects"> <object class="NSMutableArray" key="connectionRecords"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBConnectionRecord"> <object class="IBCocoaTouchOutletConnection" key="connection"> <string key="label">view</string> <reference key="source" ref="372490531"/> <reference key="destination" ref="774585933"/> </object> <int key="connectionID">7</int> </object> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchEventConnection" key="connection"> + <string key="label">gameButtonPressed:</string> + <reference key="source" ref="879414223"/> + <reference key="destination" ref="372490531"/> + <int key="IBEventType">7</int> + </object> + <int key="connectionID">13</int> + </object> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">gameViewController</string> + <reference key="source" ref="372490531"/> + <reference key="destination" ref="139201391"/> + </object> + <int key="connectionID">15</int> + </object> </object> <object class="IBMutableOrderedSet" key="objectRecords"> <object class="NSArray" key="orderedObjects"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBObjectRecord"> <int key="objectID">0</int> <reference key="object" ref="0"/> <reference key="children" ref="1000"/> <nil key="parent"/> </object> <object class="IBObjectRecord"> <int key="objectID">-1</int> <reference key="object" ref="372490531"/> <reference key="parent" ref="0"/> <string key="objectName">File's Owner</string> </object> <object class="IBObjectRecord"> <int key="objectID">-2</int> <reference key="object" ref="843779117"/> <reference key="parent" ref="0"/> </object> <object class="IBObjectRecord"> <int key="objectID">6</int> <reference key="object" ref="774585933"/> <object class="NSMutableArray" key="children"> <bool key="EncodedWithXMLCoder">YES</bool> <reference ref="1015927794"/> <reference ref="879414223"/> <reference ref="315950724"/> <reference ref="578362606"/> <reference ref="1039261273"/> </object> <reference key="parent" ref="0"/> </object> <object class="IBObjectRecord"> <int key="objectID">8</int> <reference key="object" ref="1015927794"/> <reference key="parent" ref="774585933"/> </object> <object class="IBObjectRecord"> <int key="objectID">9</int> <reference key="object" ref="879414223"/> <reference key="parent" ref="774585933"/> </object> <object class="IBObjectRecord"> <int key="objectID">10</int> <reference key="object" ref="315950724"/> <reference key="parent" ref="774585933"/> </object> <object class="IBObjectRecord"> <int key="objectID">11</int> <reference key="object" ref="1039261273"/> <reference key="parent" ref="774585933"/> </object> <object class="IBObjectRecord"> <int key="objectID">12</int> <reference key="object" ref="578362606"/> <reference key="parent" ref="774585933"/> </object> + <object class="IBObjectRecord"> + <int key="objectID">14</int> + <reference key="object" ref="139201391"/> + <reference key="parent" ref="0"/> + </object> </object> </object> <object class="NSMutableDictionary" key="flattenedProperties"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="NSArray" key="dict.sortedKeys"> <bool key="EncodedWithXMLCoder">YES</bool> <string>-1.CustomClassName</string> <string>-2.CustomClassName</string> <string>10.IBPluginDependency</string> <string>11.IBPluginDependency</string> <string>12.IBPluginDependency</string> + <string>14.CustomClassName</string> + <string>14.IBEditorWindowLastContentRect</string> + <string>14.IBPluginDependency</string> <string>6.IBEditorWindowLastContentRect</string> <string>6.IBPluginDependency</string> <string>8.IBPluginDependency</string> <string>9.IBPluginDependency</string> </object> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> <string>BalloonChallengeViewController</string> <string>UIResponder</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> - <string>{{438, 276}, {320, 480}}</string> + <string>GameViewController</string> + <string>{{391, 0}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>{{666, 276}, {320, 480}}</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> </object> </object> <object class="NSMutableDictionary" key="unlocalizedProperties"> <bool key="EncodedWithXMLCoder">YES</bool> <reference key="dict.sortedKeys" ref="0"/> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> </object> </object> <nil key="activeLocalization"/> <object class="NSMutableDictionary" key="localizations"> <bool key="EncodedWithXMLCoder">YES</bool> <reference key="dict.sortedKeys" ref="0"/> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> </object> </object> <nil key="sourceID"/> - <int key="maxID">12</int> + <int key="maxID">15</int> </object> <object class="IBClassDescriber" key="IBDocument.Classes"> <object class="NSMutableArray" key="referencedPartialClassDescriptions"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBPartialClassDescription"> <string key="className">BalloonChallengeViewController</string> <string key="superclassName">UIViewController</string> + <object class="NSMutableDictionary" key="actions"> + <string key="NS.key.0">gameButtonPressed:</string> + <string key="NS.object.0">id</string> + </object> + <object class="NSMutableDictionary" key="outlets"> + <string key="NS.key.0">gameViewController</string> + <string key="NS.object.0">GameViewController</string> + </object> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBProjectSource</string> <string key="minorKey">Classes/BalloonChallengeViewController.h</string> </object> </object> + <object class="IBPartialClassDescription"> + <string key="className">GameViewController</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">Classes/GameViewController.h</string> + </object> + </object> </object> <object class="NSMutableArray" key="referencedPartialClassDescriptionsV3.2+"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSError.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSFileManager.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSKeyValueCoding.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSKeyValueObserving.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSKeyedArchiver.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSNetServices.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSObject.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSPort.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSRunLoop.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSStream.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSThread.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSURL.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSURLConnection.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">Foundation.framework/Headers/NSXMLParser.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIAccessibility.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UINibLoading.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier" id="713855212"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIResponder.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIButton</string> <string key="superclassName">UIControl</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIButton.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIControl</string> <string key="superclassName">UIView</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIControl.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIImageView</string> <string key="superclassName">UIView</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIImageView.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIResponder</string> <string key="superclassName">NSObject</string> <reference key="sourceIdentifier" ref="713855212"/> </object> <object class="IBPartialClassDescription"> <string key="className">UISearchBar</string> <string key="superclassName">UIView</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UISearchBar.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UISearchDisplayController</string> <string key="superclassName">NSObject</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UISearchDisplayController.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIView</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UITextField.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIView</string> <string key="superclassName">UIResponder</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIView.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIViewController</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UINavigationController.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIViewController</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UITabBarController.h</string> </object> </object> <object class="IBPartialClassDescription"> <string key="className">UIViewController</string> <string key="superclassName">UIResponder</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBFrameworkSource</string> <string key="minorKey">UIKit.framework/Headers/UIViewController.h</string> </object> </object> </object> </object> <int key="IBDocument.localizationMode">0</int> <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> <integer value="3100" key="NS.object.0"/> </object> <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> <string key="IBDocument.LastKnownRelativeProjectPath">BalloonChallenge.xcodeproj</string> <int key="IBDocument.defaultPropertyAccessControl">3</int> <string key="IBCocoaTouchPluginVersion">3.1</string> </data> </archive> diff --git a/Classes/BalloonChallengeViewController.h b/Classes/BalloonChallengeViewController.h index c50f03e..55f159a 100644 --- a/Classes/BalloonChallengeViewController.h +++ b/Classes/BalloonChallengeViewController.h @@ -1,16 +1,21 @@ // // BalloonChallengeViewController.h // BalloonChallenge // // Created by Brian Wong on 2/6/10. // Copyright __MyCompanyName__ 2010. All rights reserved. // #import <UIKit/UIKit.h> +#import "GameViewController.h" @interface BalloonChallengeViewController : UIViewController { - + GameViewController *gameViewController; } +@property (nonatomic, retain) IBOutlet GameViewController *gameViewController; + +-(IBAction) gameButtonPressed: (id) sender; + @end diff --git a/Classes/BalloonChallengeViewController.m b/Classes/BalloonChallengeViewController.m index 01cdfdf..7fb352f 100644 --- a/Classes/BalloonChallengeViewController.m +++ b/Classes/BalloonChallengeViewController.m @@ -1,65 +1,69 @@ // // BalloonChallengeViewController.m // BalloonChallenge // // Created by Brian Wong on 2/6/10. // Copyright __MyCompanyName__ 2010. All rights reserved. // #import "BalloonChallengeViewController.h" @implementation BalloonChallengeViewController +@synthesize gameViewController; - +-(IBAction) gameButtonPressed: (id) sender { + [self presentModalViewController:gameViewController animated:YES]; +} /* // The designated initializer. Override to perform setup that is required before the view is loaded. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization } return self; } */ /* // Implement loadView to create a view hierarchy programmatically, without using a nib. - (void)loadView { } */ /* // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } */ /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; + gameViewController = nil; } - (void)dealloc { + [gameViewController release]; [super dealloc]; } @end diff --git a/Classes/GameViewController.h b/Classes/GameViewController.h new file mode 100644 index 0000000..d843760 --- /dev/null +++ b/Classes/GameViewController.h @@ -0,0 +1,16 @@ +// +// GameViewController.h +// BalloonChallenge +// +// Created by Kevin Weiler on 2/21/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import <UIKit/UIKit.h> + + +@interface GameViewController : UIViewController { + +} + +@end diff --git a/Classes/GameViewController.m b/Classes/GameViewController.m new file mode 100644 index 0000000..367cc51 --- /dev/null +++ b/Classes/GameViewController.m @@ -0,0 +1,57 @@ +// +// GameViewController.m +// BalloonChallenge +// +// Created by Kevin Weiler on 2/21/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import "GameViewController.h" + + +@implementation GameViewController + +/* + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { + // Custom initialization + } + return self; +} +*/ + + +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} + + +/* +// Override to allow orientations other than the default portrait orientation. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + // Return YES for supported orientations + return (interfaceOrientation == UIInterfaceOrientationPortrait); +} +*/ + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end diff --git a/Classes/GameViewController.xib b/Classes/GameViewController.xib new file mode 100644 index 0000000..f176f37 --- /dev/null +++ b/Classes/GameViewController.xib @@ -0,0 +1,447 @@ +<?xml version="1.0" encoding="UTF-8"?> +<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> + <data> + <int key="IBDocument.SystemTarget">784</int> + <string key="IBDocument.SystemVersion">10C540</string> + <string key="IBDocument.InterfaceBuilderVersion">740</string> + <string key="IBDocument.AppKitVersion">1038.25</string> + <string key="IBDocument.HIToolboxVersion">458.00</string> + <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> + <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string key="NS.object.0">62</string> + </object> + <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSArray" key="IBDocument.PluginDependencies"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + <object class="NSMutableDictionary" key="IBDocument.Metadata"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys" id="0"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBProxyObject" id="372490531"> + <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> + </object> + <object class="IBProxyObject" id="975951072"> + <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> + </object> + <object class="IBUIView" id="191373211"> + <nil key="NSNextResponder"/> + <int key="NSvFlags">292</int> + <object class="NSMutableArray" key="NSSubviews"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBUIImageView" id="359810284"> + <reference key="NSNextResponder" ref="191373211"/> + <int key="NSvFlags">274</int> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview" ref="191373211"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentMode">4</int> + <bool key="IBUIUserInteractionEnabled">NO</bool> + <object class="NSCustomResource" key="IBUIImage"> + <string key="NSClassName">NSImage</string> + <string key="NSResourceName">game_bg.png</string> + </object> + </object> + <object class="IBUIToolbar" id="770633873"> + <reference key="NSNextResponder" ref="191373211"/> + <int key="NSvFlags">266</int> + <string key="NSFrame">{{0, -6}, {320, 44}}</string> + <reference key="NSSuperview" ref="191373211"/> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentMode">8</int> + <object class="NSMutableArray" key="IBUIItems"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBUIBarButtonItem" id="1034159527"> + <string key="IBUITitle">Menu</string> + <float key="IBUIWidth">54</float> + <int key="IBUIStyle">1</int> + <reference key="IBUIToolbar" ref="770633873"/> + </object> + <object class="IBUIBarButtonItem" id="466791992"> + <string key="IBUITitle">Item</string> + <int key="IBUIStyle">1</int> + <reference key="IBUIToolbar" ref="770633873"/> + </object> + <object class="IBUIBarButtonItem" id="354558043"> + <string key="IBUITitle">Item</string> + <int key="IBUIStyle">1</int> + <reference key="IBUIToolbar" ref="770633873"/> + </object> + </object> + </object> + </object> + <string key="NSFrameSize">{320, 460}</string> + <object class="NSColor" key="IBUIBackgroundColor"> + <int key="NSColorSpace">1</int> + <bytes key="NSRGB">MSAxIDEAA</bytes> + </object> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + </object> + <object class="IBObjectContainer" key="IBDocument.Objects"> + <object class="NSMutableArray" key="connectionRecords"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">view</string> + <reference key="source" ref="372490531"/> + <reference key="destination" ref="191373211"/> + </object> + <int key="connectionID">3</int> + </object> + </object> + <object class="IBMutableOrderedSet" key="objectRecords"> + <object class="NSArray" key="orderedObjects"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBObjectRecord"> + <int key="objectID">0</int> + <reference key="object" ref="0"/> + <reference key="children" ref="1000"/> + <nil key="parent"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">1</int> + <reference key="object" ref="191373211"/> + <object class="NSMutableArray" key="children"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference ref="359810284"/> + <reference ref="770633873"/> + </object> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-1</int> + <reference key="object" ref="372490531"/> + <reference key="parent" ref="0"/> + <string key="objectName">File's Owner</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-2</int> + <reference key="object" ref="975951072"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">5</int> + <reference key="object" ref="359810284"/> + <reference key="parent" ref="191373211"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">6</int> + <reference key="object" ref="770633873"/> + <object class="NSMutableArray" key="children"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference ref="1034159527"/> + <reference ref="466791992"/> + <reference ref="354558043"/> + </object> + <reference key="parent" ref="191373211"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">7</int> + <reference key="object" ref="1034159527"/> + <reference key="parent" ref="770633873"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">8</int> + <reference key="object" ref="466791992"/> + <reference key="parent" ref="770633873"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">9</int> + <reference key="object" ref="354558043"/> + <reference key="parent" ref="770633873"/> + </object> + </object> + </object> + <object class="NSMutableDictionary" key="flattenedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>-1.CustomClassName</string> + <string>-2.CustomClassName</string> + <string>1.IBEditorWindowLastContentRect</string> + <string>1.IBPluginDependency</string> + <string>5.IBPluginDependency</string> + <string>6.IBPluginDependency</string> + <string>7.IBPluginDependency</string> + <string>8.IBPluginDependency</string> + <string>9.IBPluginDependency</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>GameViewController</string> + <string>UIResponder</string> + <string>{{482, 276}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + </object> + <object class="NSMutableDictionary" key="unlocalizedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="activeLocalization"/> + <object class="NSMutableDictionary" key="localizations"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="sourceID"/> + <int key="maxID">9</int> + </object> + <object class="IBClassDescriber" key="IBDocument.Classes"> + <object class="NSMutableArray" key="referencedPartialClassDescriptions"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">GameViewController</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">Classes/GameViewController.h</string> + </object> + </object> + </object> + <object class="NSMutableArray" key="referencedPartialClassDescriptionsV3.2+"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSError.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSFileManager.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyValueCoding.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyValueObserving.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyedArchiver.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSNetServices.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSObject.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSPort.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSRunLoop.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSStream.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSThread.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSURL.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSURLConnection.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSXMLParser.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIAccessibility.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UINibLoading.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier" id="885404994"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIResponder.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIBarButtonItem</string> + <string key="superclassName">UIBarItem</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIBarButtonItem.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIBarItem</string> + <string key="superclassName">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIBarItem.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIImageView</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIImageView.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIResponder</string> + <string key="superclassName">NSObject</string> + <reference key="sourceIdentifier" ref="885404994"/> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UISearchBar</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UISearchBar.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UISearchDisplayController</string> + <string key="superclassName">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UISearchDisplayController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIToolbar</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIToolbar.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UITextField.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIView</string> + <string key="superclassName">UIResponder</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIView.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UINavigationController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UITabBarController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <string key="superclassName">UIResponder</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIViewController.h</string> + </object> + </object> + </object> + </object> + <int key="IBDocument.localizationMode">0</int> + <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> + <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> + <integer value="3000" key="NS.object.0"/> + </object> + <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> + <string key="IBDocument.LastKnownRelativeProjectPath">../BalloonChallenge.xcodeproj</string> + <int key="IBDocument.defaultPropertyAccessControl">3</int> + <string key="IBCocoaTouchPluginVersion">3.1</string> + </data> +</archive> diff --git a/blue_balloon.png b/blue_balloon.png new file mode 100644 index 0000000..f7095a5 Binary files /dev/null and b/blue_balloon.png differ diff --git a/blue_balloon.psd b/blue_balloon.psd new file mode 100644 index 0000000..f604607 Binary files /dev/null and b/blue_balloon.psd differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree index bfb9fc7..1dd21b8 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree index cab5da8..06a50d6 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree index 9e884d4..c9a5ecb 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree index 387dd88..23cd942 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header index 1a2d9b4..91c8824 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree index 34227ed..0f70de1 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control index 29fdf6a..c88ec78 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings index fca2b19..55f849a 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree index 3609212..09f5c64 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols index b478e7e..eebff96 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols differ
bwong/BalloonChallenge
f4f25686bdf58e2865df0111297e820646f03db8
added new view controller classes
diff --git a/BalloonChallenge.xcodeproj/bwong.mode1v3 b/BalloonChallenge.xcodeproj/bwong.mode1v3 index 7a4599c..2ecf0f8 100644 --- a/BalloonChallenge.xcodeproj/bwong.mode1v3 +++ b/BalloonChallenge.xcodeproj/bwong.mode1v3 @@ -1,1111 +1,1127 @@ <?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>ActivePerspectiveName</key> <string>Project</string> <key>AllowedModules</key> <array> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Name</key> <string>Groups and Files Outline View</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Name</key> <string>Editor</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCTaskListModule</string> <key>Name</key> <string>Task List</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCDetailModule</string> <key>Name</key> <string>File and Smart Group Detail Viewer</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXBuildResultsModule</string> <key>Name</key> <string>Detailed Build Results Viewer</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXProjectFindModule</string> <key>Name</key> <string>Project Batch Find Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCProjectFormatConflictsModule</string> <key>Name</key> <string>Project Format Conflicts List</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXBookmarksModule</string> <key>Name</key> <string>Bookmarks Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXClassBrowserModule</string> <key>Name</key> <string>Class Browser</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXCVSModule</string> <key>Name</key> <string>Source Code Control Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXDebugBreakpointsModule</string> <key>Name</key> <string>Debug Breakpoints Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCDockableInspector</string> <key>Name</key> <string>Inspector</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>PBXOpenQuicklyModule</string> <key>Name</key> <string>Open Quickly Tool</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXDebugSessionModule</string> <key>Name</key> <string>Debugger</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>1</string> <key>Module</key> <string>PBXDebugCLIModule</string> <key>Name</key> <string>Debug Console</string> </dict> <dict> <key>BundleLoadPath</key> <string></string> <key>MaxInstances</key> <string>n</string> <key>Module</key> <string>XCSnapshotModule</string> <key>Name</key> <string>Snapshots Tool</string> </dict> </array> <key>BundlePath</key> <string>/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources</string> <key>Description</key> <string>DefaultDescriptionKey</string> <key>DockingSystemVisible</key> <false/> <key>Extension</key> <string>mode1v3</string> <key>FavBarConfig</key> <dict> <key>PBXProjectModuleGUID</key> <string>1D6E99AE111D83EB00661416</string> <key>XCBarModuleItemNames</key> <dict/> <key>XCBarModuleItems</key> <array/> </dict> <key>FirstTimeWindowDisplayed</key> <false/> <key>Identifier</key> <string>com.apple.perspectives.project.mode1v3</string> <key>MajorVersion</key> <integer>33</integer> <key>MinorVersion</key> <integer>0</integer> <key>Name</key> <string>Default</string> <key>Notifications</key> <array/> <key>OpenEditors</key> <array/> <key>PerspectiveWidths</key> <array> <integer>-1</integer> <integer>-1</integer> </array> <key>Perspectives</key> <array> <dict> <key>ChosenToolbarItems</key> <array> <string>active-combo-popup</string> <string>action</string> <string>NSToolbarFlexibleSpaceItem</string> <string>debugger-enable-breakpoints</string> <string>build-and-go</string> <string>com.apple.ide.PBXToolbarStopButton</string> <string>get-info</string> <string>NSToolbarFlexibleSpaceItem</string> <string>com.apple.pbx.toolbar.searchfield</string> </array> <key>ControllerClassBaseName</key> <string></string> <key>IconName</key> <string>WindowOfProjectWithEditor</string> <key>Identifier</key> <string>perspective.project</string> <key>IsVertical</key> <false/> <key>Layout</key> <array> <dict> <key>BecomeActive</key> <true/> <key>ContentConfiguration</key> <dict> <key>PBXBottomSmartGroupGIDs</key> <array> <string>1C37FBAC04509CD000000102</string> <string>1C37FAAC04509CD000000102</string> <string>1C37FABC05509CD000000102</string> <string>1C37FABC05539CD112110102</string> <string>E2644B35053B69B200211256</string> <string>1C37FABC04509CD000100104</string> <string>1CC0EA4004350EF90044410B</string> <string>1CC0EA4004350EF90041110B</string> </array> <key>PBXProjectModuleGUID</key> <string>1CE0B1FE06471DED0097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Files</string> <key>PBXProjectStructureProvided</key> <string>yes</string> <key>PBXSmartGroupTreeModuleColumnData</key> <dict> <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> <array> <real>186</real> </array> <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> <array> <string>MainColumn</string> </array> </dict> <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> <dict> <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> <array> <string>29B97314FDCFA39411CA2CEA</string> + <string>080E96DDFE201D6D7F000001</string> + <string>29B97317FDCFA39411CA2CEA</string> <string>1C37FABC05509CD000000102</string> </array> <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> <array> <array> + <integer>5</integer> + <integer>1</integer> <integer>0</integer> </array> </array> <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> <string>{{0, 0}, {186, 445}}</string> </dict> <key>PBXTopSmartGroupGIDs</key> <array/> <key>XCIncludePerspectivesSwitch</key> <true/> <key>XCSharingToken</key> <string>com.apple.Xcode.GFSharingToken</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {203, 463}}</string> <key>GroupTreeTableConfiguration</key> <array> <string>MainColumn</string> <real>186</real> </array> <key>RubberWindowFrame</key> <string>267 211 788 504 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Proportion</key> <string>203pt</string> </dict> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CE0B20306471E060097A5F4</string> <key>PBXProjectModuleLabel</key> - <string>MyNewFile14.java</string> + <string>BalloonChallengeViewController.m</string> <key>PBXSplitModuleInNavigatorKey</key> <dict> <key>Split0</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CE0B20406471E060097A5F4</string> <key>PBXProjectModuleLabel</key> - <string>MyNewFile14.java</string> + <string>BalloonChallengeViewController.m</string> + <key>_historyCapacity</key> + <integer>0</integer> + <key>bookmark</key> + <string>1D3A6784112292F700C55F47</string> + <key>history</key> + <array> + <string>1D8874B511228F3900700392</string> + <string>1D8874B611228F3900700392</string> + <string>1D8874B711228F3900700392</string> + <string>1D8874B811228F3900700392</string> + <string>1D8874BA11228F3900700392</string> + </array> </dict> <key>SplitCount</key> <string>1</string> </dict> <key>StatusBarVisibility</key> <true/> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> - <string>{{0, 0}, {580, 277}}</string> + <string>{{0, 0}, {580, 260}}</string> <key>RubberWindowFrame</key> <string>267 211 788 504 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> - <string>277pt</string> + <string>260pt</string> </dict> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CE0B20506471E060097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Detail</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> - <string>{{0, 282}, {580, 181}}</string> + <string>{{0, 265}, {580, 198}}</string> <key>RubberWindowFrame</key> <string>267 211 788 504 0 0 1280 778 </string> </dict> <key>Module</key> <string>XCDetailModule</string> <key>Proportion</key> - <string>181pt</string> + <string>198pt</string> </dict> </array> <key>Proportion</key> <string>580pt</string> </dict> </array> <key>Name</key> <string>Project</string> <key>ServiceClasses</key> <array> <string>XCModuleDock</string> <string>PBXSmartGroupTreeModule</string> <string>XCModuleDock</string> <string>PBXNavigatorGroup</string> <string>XCDetailModule</string> </array> <key>TableOfContents</key> <array> - <string>1D6E99AC111D83EB00661416</string> + <string>1D3A6785112292F700C55F47</string> <string>1CE0B1FE06471DED0097A5F4</string> - <string>1D6E99AD111D83EB00661416</string> + <string>1D3A6786112292F700C55F47</string> <string>1CE0B20306471E060097A5F4</string> <string>1CE0B20506471E060097A5F4</string> </array> <key>ToolbarConfigUserDefaultsMinorVersion</key> <string>2</string> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.defaultV3</string> </dict> <dict> <key>ControllerClassBaseName</key> <string></string> <key>IconName</key> <string>WindowOfProject</string> <key>Identifier</key> <string>perspective.morph</string> <key>IsVertical</key> <integer>0</integer> <key>Layout</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXBottomSmartGroupGIDs</key> <array> <string>1C37FBAC04509CD000000102</string> <string>1C37FAAC04509CD000000102</string> <string>1C08E77C0454961000C914BD</string> <string>1C37FABC05509CD000000102</string> <string>1C37FABC05539CD112110102</string> <string>E2644B35053B69B200211256</string> <string>1C37FABC04509CD000100104</string> <string>1CC0EA4004350EF90044410B</string> <string>1CC0EA4004350EF90041110B</string> </array> <key>PBXProjectModuleGUID</key> <string>11E0B1FE06471DED0097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Files</string> <key>PBXProjectStructureProvided</key> <string>yes</string> <key>PBXSmartGroupTreeModuleColumnData</key> <dict> <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> <array> <real>186</real> </array> <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> <array> <string>MainColumn</string> </array> </dict> <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> <dict> <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> <array> <string>29B97314FDCFA39411CA2CEA</string> <string>1C37FABC05509CD000000102</string> </array> <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> <array> <array> <integer>0</integer> </array> </array> <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> <string>{{0, 0}, {186, 337}}</string> </dict> <key>PBXTopSmartGroupGIDs</key> <array/> <key>XCIncludePerspectivesSwitch</key> <integer>1</integer> <key>XCSharingToken</key> <string>com.apple.Xcode.GFSharingToken</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {203, 355}}</string> <key>GroupTreeTableConfiguration</key> <array> <string>MainColumn</string> <real>186</real> </array> <key>RubberWindowFrame</key> <string>373 269 690 397 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Morph</string> <key>PreferredWidth</key> <integer>300</integer> <key>ServiceClasses</key> <array> <string>XCModuleDock</string> <string>PBXSmartGroupTreeModule</string> </array> <key>TableOfContents</key> <array> <string>11E0B1FE06471DED0097A5F4</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.default.shortV3</string> </dict> </array> <key>PerspectivesBarVisible</key> <false/> <key>ShelfIsVisible</key> <false/> <key>SourceDescription</key> <string>file at '/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources/XCPerspectivesSpecificationMode1.xcperspec'</string> <key>StatusbarIsVisible</key> <true/> <key>TimeStamp</key> <real>0.0</real> <key>ToolbarConfigUserDefaultsMinorVersion</key> <string>2</string> <key>ToolbarDisplayMode</key> <integer>1</integer> <key>ToolbarIsVisible</key> <true/> <key>ToolbarSizeMode</key> <integer>1</integer> <key>Type</key> <string>Perspectives</string> <key>UpdateMessage</key> <string>The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'?</string> <key>WindowJustification</key> <integer>5</integer> <key>WindowOrderList</key> <array> <string>1D6E99AF111D83EB00661416</string> <string>/Users/bwong/Documents/COEN296/BalloonChallenge/BalloonChallenge.xcodeproj</string> </array> <key>WindowString</key> <string>267 211 788 504 0 0 1280 778 </string> <key>WindowToolsV3</key> <array> <dict> <key>FirstTimeWindowDisplayed</key> <false/> <key>Identifier</key> <string>windowTool.build</string> <key>IsVertical</key> <true/> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD0528F0623707200166675</string> <key>PBXProjectModuleLabel</key> <string></string> <key>StatusBarVisibility</key> <true/> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {500, 218}}</string> <key>RubberWindowFrame</key> <string>288 192 500 500 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>218pt</string> </dict> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>XCMainBuildResultsModuleGUID</string> <key>PBXProjectModuleLabel</key> <string>Build Results</string> <key>XCBuildResultsTrigger_Collapse</key> <integer>1021</integer> <key>XCBuildResultsTrigger_Open</key> <integer>1011</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 223}, {500, 236}}</string> <key>RubberWindowFrame</key> <string>288 192 500 500 0 0 1280 778 </string> </dict> <key>Module</key> <string>PBXBuildResultsModule</string> <key>Proportion</key> <string>236pt</string> </dict> </array> <key>Proportion</key> <string>459pt</string> </dict> </array> <key>Name</key> <string>Build Results</string> <key>ServiceClasses</key> <array> <string>PBXBuildResultsModule</string> </array> <key>StatusbarIsVisible</key> <true/> <key>TableOfContents</key> <array> <string>1D6E99AF111D83EB00661416</string> - <string>1D6E99B0111D83EB00661416</string> + <string>1D3A6787112292F700C55F47</string> <string>1CD0528F0623707200166675</string> <string>XCMainBuildResultsModuleGUID</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.buildV3</string> <key>WindowContentMinSize</key> <string>486 300</string> <key>WindowString</key> <string>288 192 500 500 0 0 1280 778 </string> <key>WindowToolGUID</key> <string>1D6E99AF111D83EB00661416</string> <key>WindowToolIsVisible</key> <false/> </dict> <dict> <key>Identifier</key> <string>windowTool.debugger</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>Debugger</key> <dict> <key>HorizontalSplitView</key> <dict> <key>_collapsingFrameDimension</key> <real>0.0</real> <key>_indexOfCollapsedView</key> <integer>0</integer> <key>_percentageOfCollapsedView</key> <real>0.0</real> <key>isCollapsed</key> <string>yes</string> <key>sizes</key> <array> <string>{{0, 0}, {317, 164}}</string> <string>{{317, 0}, {377, 164}}</string> </array> </dict> <key>VerticalSplitView</key> <dict> <key>_collapsingFrameDimension</key> <real>0.0</real> <key>_indexOfCollapsedView</key> <integer>0</integer> <key>_percentageOfCollapsedView</key> <real>0.0</real> <key>isCollapsed</key> <string>yes</string> <key>sizes</key> <array> <string>{{0, 0}, {694, 164}}</string> <string>{{0, 164}, {694, 216}}</string> </array> </dict> </dict> <key>LauncherConfigVersion</key> <string>8</string> <key>PBXProjectModuleGUID</key> <string>1C162984064C10D400B95A72</string> <key>PBXProjectModuleLabel</key> <string>Debug - GLUTExamples (Underwater)</string> </dict> <key>GeometryConfiguration</key> <dict> <key>DebugConsoleDrawerSize</key> <string>{100, 120}</string> <key>DebugConsoleVisible</key> <string>None</string> <key>DebugConsoleWindowFrame</key> <string>{{200, 200}, {500, 300}}</string> <key>DebugSTDIOWindowFrame</key> <string>{{200, 200}, {500, 300}}</string> <key>Frame</key> <string>{{0, 0}, {694, 380}}</string> <key>RubberWindowFrame</key> <string>321 238 694 422 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXDebugSessionModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Debugger</string> <key>ServiceClasses</key> <array> <string>PBXDebugSessionModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1CD10A99069EF8BA00B06720</string> <string>1C0AD2AB069F1E9B00FABCE6</string> <string>1C162984064C10D400B95A72</string> <string>1C0AD2AC069F1E9B00FABCE6</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.debugV3</string> <key>WindowString</key> <string>321 238 694 422 0 0 1440 878 </string> <key>WindowToolGUID</key> <string>1CD10A99069EF8BA00B06720</string> <key>WindowToolIsVisible</key> <integer>0</integer> </dict> <dict> <key>Identifier</key> <string>windowTool.find</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CDD528C0622207200134675</string> <key>PBXProjectModuleLabel</key> <string>&lt;No Editor&gt;</string> <key>PBXSplitModuleInNavigatorKey</key> <dict> <key>Split0</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD0528D0623707200166675</string> </dict> <key>SplitCount</key> <string>1</string> </dict> <key>StatusBarVisibility</key> <integer>1</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {781, 167}}</string> <key>RubberWindowFrame</key> <string>62 385 781 470 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>781pt</string> </dict> </array> <key>Proportion</key> <string>50%</string> </dict> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD0528E0623707200166675</string> <key>PBXProjectModuleLabel</key> <string>Project Find</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{8, 0}, {773, 254}}</string> <key>RubberWindowFrame</key> <string>62 385 781 470 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXProjectFindModule</string> <key>Proportion</key> <string>50%</string> </dict> </array> <key>Proportion</key> <string>428pt</string> </dict> </array> <key>Name</key> <string>Project Find</string> <key>ServiceClasses</key> <array> <string>PBXProjectFindModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1C530D57069F1CE1000CFCEE</string> <string>1C530D58069F1CE1000CFCEE</string> <string>1C530D59069F1CE1000CFCEE</string> <string>1CDD528C0622207200134675</string> <string>1C530D5A069F1CE1000CFCEE</string> <string>1CE0B1FE06471DED0097A5F4</string> <string>1CD0528E0623707200166675</string> </array> <key>WindowString</key> <string>62 385 781 470 0 0 1440 878 </string> <key>WindowToolGUID</key> <string>1C530D57069F1CE1000CFCEE</string> <key>WindowToolIsVisible</key> <integer>0</integer> </dict> <dict> <key>Identifier</key> <string>MENUSEPARATOR</string> </dict> <dict> <key>Identifier</key> <string>windowTool.debuggerConsole</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1C78EAAC065D492600B07095</string> <key>PBXProjectModuleLabel</key> <string>Debugger Console</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {650, 250}}</string> <key>RubberWindowFrame</key> <string>516 632 650 250 0 0 1680 1027 </string> </dict> <key>Module</key> <string>PBXDebugCLIModule</string> <key>Proportion</key> <string>209pt</string> </dict> </array> <key>Proportion</key> <string>209pt</string> </dict> </array> <key>Name</key> <string>Debugger Console</string> <key>ServiceClasses</key> <array> <string>PBXDebugCLIModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1C78EAAD065D492600B07095</string> <string>1C78EAAE065D492600B07095</string> <string>1C78EAAC065D492600B07095</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.consoleV3</string> <key>WindowString</key> <string>650 41 650 250 0 0 1280 1002 </string> <key>WindowToolGUID</key> <string>1C78EAAD065D492600B07095</string> <key>WindowToolIsVisible</key> <integer>0</integer> </dict> <dict> <key>Identifier</key> <string>windowTool.snapshots</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>Module</key> <string>XCSnapshotModule</string> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Proportion</key> <string>100%</string> </dict> </array> <key>Name</key> <string>Snapshots</string> <key>ServiceClasses</key> <array> <string>XCSnapshotModule</string> </array> <key>StatusbarIsVisible</key> <string>Yes</string> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.snapshots</string> <key>WindowString</key> <string>315 824 300 550 0 0 1440 878 </string> <key>WindowToolIsVisible</key> <string>Yes</string> </dict> <dict> <key>Identifier</key> <string>windowTool.scm</string> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1C78EAB2065D492600B07095</string> <key>PBXProjectModuleLabel</key> <string>&lt;No Editor&gt;</string> <key>PBXSplitModuleInNavigatorKey</key> <dict> <key>Split0</key> <dict> <key>PBXProjectModuleGUID</key> <string>1C78EAB3065D492600B07095</string> </dict> <key>SplitCount</key> <string>1</string> </dict> <key>StatusBarVisibility</key> <integer>1</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {452, 0}}</string> <key>RubberWindowFrame</key> <string>743 379 452 308 0 0 1280 1002 </string> </dict> <key>Module</key> <string>PBXNavigatorGroup</string> <key>Proportion</key> <string>0pt</string> </dict> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CD052920623707200166675</string> <key>PBXProjectModuleLabel</key> <string>SCM</string> </dict> <key>GeometryConfiguration</key> <dict> <key>ConsoleFrame</key> <string>{{0, 259}, {452, 0}}</string> <key>Frame</key> <string>{{0, 7}, {452, 259}}</string> <key>RubberWindowFrame</key> <string>743 379 452 308 0 0 1280 1002 </string> <key>TableConfiguration</key> <array> <string>Status</string> <real>30</real> <string>FileName</string> <real>199</real> <string>Path</string> <real>197.0950012207031</real> </array> <key>TableFrame</key> <string>{{0, 0}, {452, 250}}</string> </dict> <key>Module</key> <string>PBXCVSModule</string> <key>Proportion</key> <string>262pt</string> </dict> </array> <key>Proportion</key> <string>266pt</string> </dict> </array> <key>Name</key> <string>SCM</string> <key>ServiceClasses</key> <array> <string>PBXCVSModule</string> </array> <key>StatusbarIsVisible</key> <integer>1</integer> <key>TableOfContents</key> <array> <string>1C78EAB4065D492600B07095</string> <string>1C78EAB5065D492600B07095</string> <string>1C78EAB2065D492600B07095</string> <string>1CD052920623707200166675</string> </array> <key>ToolbarConfiguration</key> <string>xcode.toolbar.config.scm</string> <key>WindowString</key> <string>743 379 452 308 0 0 1280 1002 </string> </dict> <dict> <key>Identifier</key> <string>windowTool.breakpoints</string> <key>IsVertical</key> <integer>0</integer> <key>Layout</key> <array> <dict> <key>Dock</key> <array> <dict> <key>BecomeActive</key> <integer>1</integer> <key>ContentConfiguration</key> <dict> <key>PBXBottomSmartGroupGIDs</key> <array> <string>1C77FABC04509CD000000102</string> </array> <key>PBXProjectModuleGUID</key> <string>1CE0B1FE06471DED0097A5F4</string> <key>PBXProjectModuleLabel</key> <string>Files</string> <key>PBXProjectStructureProvided</key> <string>no</string> <key>PBXSmartGroupTreeModuleColumnData</key> <dict> <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> <array> <real>168</real> </array> <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> <array> <string>MainColumn</string> </array> </dict> <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> <dict> <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> <array> <string>1C77FABC04509CD000000102</string> </array> <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> <array> <array> <integer>0</integer> </array> </array> <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> <string>{{0, 0}, {168, 350}}</string> </dict> <key>PBXTopSmartGroupGIDs</key> <array/> <key>XCIncludePerspectivesSwitch</key> <integer>0</integer> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{0, 0}, {185, 368}}</string> <key>GroupTreeTableConfiguration</key> <array> <string>MainColumn</string> <real>168</real> </array> <key>RubberWindowFrame</key> <string>315 424 744 409 0 0 1440 878 </string> </dict> <key>Module</key> <string>PBXSmartGroupTreeModule</string> <key>Proportion</key> <string>185pt</string> </dict> <dict> <key>ContentConfiguration</key> <dict> <key>PBXProjectModuleGUID</key> <string>1CA1AED706398EBD00589147</string> <key>PBXProjectModuleLabel</key> <string>Detail</string> </dict> <key>GeometryConfiguration</key> <dict> <key>Frame</key> <string>{{190, 0}, {554, 368}}</string> <key>RubberWindowFrame</key> <string>315 424 744 409 0 0 1440 878 </string> </dict> <key>Module</key> <string>XCDetailModule</string> <key>Proportion</key> <string>554pt</string> </dict> </array> <key>Proportion</key> <string>368pt</string> </dict> </array> <key>MajorVersion</key> <integer>3</integer> <key>MinorVersion</key> diff --git a/BalloonChallenge.xcodeproj/bwong.pbxuser b/BalloonChallenge.xcodeproj/bwong.pbxuser index 144d059..ea97eb5 100644 --- a/BalloonChallenge.xcodeproj/bwong.pbxuser +++ b/BalloonChallenge.xcodeproj/bwong.pbxuser @@ -1,88 +1,206 @@ // !$*UTF8*$! { + 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {614, 299}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 523}"; + }; + }; + 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {519, 390}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 418}"; + }; + }; + 1D3A6784112292F700C55F47 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; + name = "BalloonChallengeViewController.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 522; + vrLoc = 0; + }; + 1D3A678A1122975D00C55F47 /* OptionsViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {519, 228}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 244}"; + }; + }; + 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {519, 228}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 250}"; + }; + }; 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { activeExec = 0; executables = ( 1D6E99A8111D83E700661416 /* BalloonChallenge */, ); }; 1D6E99A8111D83E700661416 /* BalloonChallenge */ = { isa = PBXExecutable; activeArgIndices = ( ); argumentStrings = ( ); autoAttachOnCrash = 1; breakpointsEnabled = 0; configStateDict = { }; customDataFormattersEnabled = 1; dataTipCustomDataFormattersEnabled = 1; dataTipShowTypeColumn = 1; dataTipSortType = 0; debuggerPlugin = GDBDebugging; disassemblyDisplayState = 0; enableDebugStr = 1; environmentEntries = ( ); executableSystemSymbolLevel = 0; executableUserSymbolLevel = 0; libgmallocEnabled = 0; name = BalloonChallenge; showTypeColumn = 0; sourceDirectories = ( ); }; 1D6E99B1111D83EB00661416 /* Source Control */ = { isa = PBXSourceControlManager; fallbackIsa = XCSourceControlManager; isSCMEnabled = 0; scmConfiguration = { repositoryNamesForRoots = { "" = ""; }; }; }; 1D6E99B2111D83EB00661416 /* Code sense */ = { isa = PBXCodeSenseManager; indexTemplatePath = ""; }; + 1D8874B511228F3900700392 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */; + name = "BalloonChallengeAppDelegate.h: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 523; + vrLoc = 0; + }; + 1D8874B611228F3900700392 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; + name = "BalloonChallengeAppDelegate.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 418; + vrLoc = 0; + }; + 1D8874B711228F3900700392 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */; + name = "BalloonChallengeViewController.h: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 262; + vrLoc = 0; + }; + 1D8874B811228F3900700392 /* PBXBookmark */ = { + isa = PBXBookmark; + fRef = 0A24546811214737009A536A /* game_bg.png */; + }; + 1D8874B911228F3900700392 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; + name = "BalloonChallengeViewController.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 555; + vrLoc = 0; + }; + 1D8874BA11228F3900700392 /* PBXTextBookmark */ = { + isa = PBXTextBookmark; + fRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; + name = "BalloonChallengeViewController.m: 1"; + rLen = 0; + rLoc = 0; + rType = 0; + vrLen = 555; + vrLoc = 0; + }; + 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {519, 237}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 262}"; + }; + }; + 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = { + uiCtxt = { + sepNavIntBoundsRect = "{{0, 0}, {712, 806}}"; + sepNavSelRange = "{0, 0}"; + sepNavVisRange = "{0, 522}"; + }; + }; 29B97313FDCFA39411CA2CEA /* Project object */ = { activeBuildConfigurationName = Debug; activeExecutable = 1D6E99A8111D83E700661416 /* BalloonChallenge */; activeTarget = 1D6058900D05DD3D006BFB54 /* BalloonChallenge */; + addToTargets = ( + 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, + ); codeSenseManager = 1D6E99B2111D83EB00661416 /* Code sense */; executables = ( 1D6E99A8111D83E700661416 /* BalloonChallenge */, ); perUserDictionary = { PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; PBXFileTableDataSourceColumnWidthsKey = ( 20, 341, 20, - 48.16259765625, + 48, 43, 43, 20, ); PBXFileTableDataSourceColumnsKey = ( PBXFileDataSource_FiletypeID, PBXFileDataSource_Filename_ColumnID, PBXFileDataSource_Built_ColumnID, PBXFileDataSource_ObjectSize_ColumnID, PBXFileDataSource_Errors_ColumnID, PBXFileDataSource_Warnings_ColumnID, PBXFileDataSource_Target_ColumnID, ); }; - PBXPerProjectTemplateStateSaveDate = 287146983; - PBXWorkspaceStateSaveDate = 287146983; + PBXPerProjectTemplateStateSaveDate = 287478498; + PBXWorkspaceStateSaveDate = 287478498; + }; + perUserProjectItems = { + 1D3A6784112292F700C55F47 /* PBXTextBookmark */ = 1D3A6784112292F700C55F47 /* PBXTextBookmark */; + 1D8874B511228F3900700392 = 1D8874B511228F3900700392 /* PBXTextBookmark */; + 1D8874B611228F3900700392 = 1D8874B611228F3900700392 /* PBXTextBookmark */; + 1D8874B711228F3900700392 = 1D8874B711228F3900700392 /* PBXTextBookmark */; + 1D8874B811228F3900700392 = 1D8874B811228F3900700392 /* PBXBookmark */; + 1D8874B911228F3900700392 = 1D8874B911228F3900700392 /* PBXTextBookmark */; + 1D8874BA11228F3900700392 = 1D8874BA11228F3900700392 /* PBXTextBookmark */; }; sourceControlManager = 1D6E99B1111D83EB00661416 /* Source Control */; userBuildSettings = { }; }; } diff --git a/BalloonChallenge.xcodeproj/project.pbxproj b/BalloonChallenge.xcodeproj/project.pbxproj index dba0e70..8fda9ce 100755 --- a/BalloonChallenge.xcodeproj/project.pbxproj +++ b/BalloonChallenge.xcodeproj/project.pbxproj @@ -1,263 +1,273 @@ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 45; objects = { /* Begin PBXBuildFile section */ - 0A24545211213B88009A536A /* GameView.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A24545011213B88009A536A /* GameView.m */; }; - 0A24545311213B88009A536A /* GameView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0A24545111213B88009A536A /* GameView.xib */; }; 0A24546911214737009A536A /* game_bg.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A24546811214737009A536A /* game_bg.png */; }; 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; }; + 1D3A678D1122975D00C55F47 /* OptionsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3A678B1122975D00C55F47 /* OptionsViewController.m */; }; + 1D3A678E1122975D00C55F47 /* OptionsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1D3A678C1122975D00C55F47 /* OptionsViewController.xib */; }; + 1D3A679D112297CA00C55F47 /* HighScoresViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */; }; + 1D3A679E112297CA00C55F47 /* HighScoresViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1D3A679C112297CA00C55F47 /* HighScoresViewController.xib */; }; 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; }; 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */; }; 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 28AD733E0D9D9553002E5188 /* MainWindow.xib */; }; 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ - 0A24544F11213B88009A536A /* GameView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameView.h; sourceTree = "<group>"; }; - 0A24545011213B88009A536A /* GameView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GameView.m; sourceTree = "<group>"; }; - 0A24545111213B88009A536A /* GameView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = GameView.xib; path = Classes/GameView.xib; sourceTree = "<group>"; }; 0A24546811214737009A536A /* game_bg.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = game_bg.png; sourceTree = "<group>"; }; 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeAppDelegate.h; sourceTree = "<group>"; }; 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeAppDelegate.m; sourceTree = "<group>"; }; + 1D3A678A1122975D00C55F47 /* OptionsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OptionsViewController.h; sourceTree = "<group>"; }; + 1D3A678B1122975D00C55F47 /* OptionsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OptionsViewController.m; sourceTree = "<group>"; }; + 1D3A678C1122975D00C55F47 /* OptionsViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = OptionsViewController.xib; path = Classes/OptionsViewController.xib; sourceTree = "<group>"; }; + 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HighScoresViewController.h; sourceTree = "<group>"; }; + 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HighScoresViewController.m; sourceTree = "<group>"; }; + 1D3A679C112297CA00C55F47 /* HighScoresViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = HighScoresViewController.xib; path = Classes/HighScoresViewController.xib; sourceTree = "<group>"; }; 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BalloonChallenge.app; sourceTree = BUILT_PRODUCTS_DIR; }; 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = BalloonChallengeViewController.xib; sourceTree = "<group>"; }; 28AD733E0D9D9553002E5188 /* MainWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MainWindow.xib; sourceTree = "<group>"; }; 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeViewController.h; sourceTree = "<group>"; }; 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeViewController.m; sourceTree = "<group>"; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallenge_Prefix.pch; sourceTree = "<group>"; }; 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "BalloonChallenge-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 080E96DDFE201D6D7F000001 /* Classes */ = { isa = PBXGroup; children = ( 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */, 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */, 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */, 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */, - 0A24544F11213B88009A536A /* GameView.h */, - 0A24545011213B88009A536A /* GameView.m */, + 1D3A678A1122975D00C55F47 /* OptionsViewController.h */, + 1D3A678B1122975D00C55F47 /* OptionsViewController.m */, + 1D3A679A112297CA00C55F47 /* HighScoresViewController.h */, + 1D3A679B112297CA00C55F47 /* HighScoresViewController.m */, ); path = Classes; sourceTree = "<group>"; }; 19C28FACFE9D520D11CA2CBB /* Products */ = { isa = PBXGroup; children = ( 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */, ); name = Products; sourceTree = "<group>"; }; 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { isa = PBXGroup; children = ( 080E96DDFE201D6D7F000001 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, 29B97317FDCFA39411CA2CEA /* Resources */, 29B97323FDCFA39411CA2CEA /* Frameworks */, 19C28FACFE9D520D11CA2CBB /* Products */, ); name = CustomTemplate; sourceTree = "<group>"; }; 29B97315FDCFA39411CA2CEA /* Other Sources */ = { isa = PBXGroup; children = ( 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */, 29B97316FDCFA39411CA2CEA /* main.m */, ); name = "Other Sources"; sourceTree = "<group>"; }; 29B97317FDCFA39411CA2CEA /* Resources */ = { isa = PBXGroup; children = ( + 1D3A679C112297CA00C55F47 /* HighScoresViewController.xib */, 0A24546811214737009A536A /* game_bg.png */, - 0A24545111213B88009A536A /* GameView.xib */, 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */, 28AD733E0D9D9553002E5188 /* MainWindow.xib */, + 1D3A678C1122975D00C55F47 /* OptionsViewController.xib */, 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */, ); name = Resources; sourceTree = "<group>"; }; 29B97323FDCFA39411CA2CEA /* Frameworks */ = { isa = PBXGroup; children = ( 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, 1D30AB110D05D00D00671497 /* Foundation.framework */, 288765A40DF7441C002DB57D /* CoreGraphics.framework */, ); name = Frameworks; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { isa = PBXNativeTarget; buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */; buildPhases = ( 1D60588D0D05DD3D006BFB54 /* Resources */, 1D60588E0D05DD3D006BFB54 /* Sources */, 1D60588F0D05DD3D006BFB54 /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = BalloonChallenge; productName = BalloonChallenge; productReference = 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */; compatibilityVersion = "Xcode 3.1"; hasScannedForEncodings = 1; mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; projectDirPath = ""; projectRoot = ""; targets = ( 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 1D60588D0D05DD3D006BFB54 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */, 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */, - 0A24545311213B88009A536A /* GameView.xib in Resources */, 0A24546911214737009A536A /* game_bg.png in Resources */, + 1D3A678E1122975D00C55F47 /* OptionsViewController.xib in Resources */, + 1D3A679E112297CA00C55F47 /* HighScoresViewController.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 1D60588E0D05DD3D006BFB54 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 1D60589B0D05DD56006BFB54 /* main.m in Sources */, 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */, 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */, - 0A24545211213B88009A536A /* GameView.m in Sources */, + 1D3A678D1122975D00C55F47 /* OptionsViewController.m in Sources */, + 1D3A679D112297CA00C55F47 /* HighScoresViewController.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 1D6058940D05DD3E006BFB54 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Debug; }; 1D6058950D05DD3E006BFB54 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Release; }; C01FCF4F08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Debug; }; C01FCF5008A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( 1D6058940D05DD3E006BFB54 /* Debug */, 1D6058950D05DD3E006BFB54 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( C01FCF4F08A954540054247B /* Debug */, C01FCF5008A954540054247B /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; } diff --git a/Classes/HighScoresViewController.h b/Classes/HighScoresViewController.h new file mode 100644 index 0000000..64b497c --- /dev/null +++ b/Classes/HighScoresViewController.h @@ -0,0 +1,16 @@ +// +// HighScoresViewController.h +// BalloonChallenge +// +// Created by Brian Wong on 2/9/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import <UIKit/UIKit.h> + + +@interface HighScoresViewController : UIViewController { + +} + +@end diff --git a/Classes/HighScoresViewController.m b/Classes/HighScoresViewController.m new file mode 100644 index 0000000..df4fb79 --- /dev/null +++ b/Classes/HighScoresViewController.m @@ -0,0 +1,57 @@ +// +// HighScoresViewController.m +// BalloonChallenge +// +// Created by Brian Wong on 2/9/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import "HighScoresViewController.h" + + +@implementation HighScoresViewController + +/* + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { + // Custom initialization + } + return self; +} +*/ + +/* +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} +*/ + +/* +// Override to allow orientations other than the default portrait orientation. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + // Return YES for supported orientations + return (interfaceOrientation == UIInterfaceOrientationPortrait); +} +*/ + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end diff --git a/Classes/HighScoresViewController.xib b/Classes/HighScoresViewController.xib new file mode 100644 index 0000000..4b1fe67 --- /dev/null +++ b/Classes/HighScoresViewController.xib @@ -0,0 +1,150 @@ +<?xml version="1.0" encoding="UTF-8"?> +<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> + <data> + <int key="IBDocument.SystemTarget">784</int> + <string key="IBDocument.SystemVersion">10A394</string> + <string key="IBDocument.InterfaceBuilderVersion">732</string> + <string key="IBDocument.AppKitVersion">1027.1</string> + <string key="IBDocument.HIToolboxVersion">430.00</string> + <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> + <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string key="NS.object.0">60</string> + </object> + <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> + <bool key="EncodedWithXMLCoder">YES</bool> + <integer value="1"/> + </object> + <object class="NSArray" key="IBDocument.PluginDependencies"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + <object class="NSMutableDictionary" key="IBDocument.Metadata"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys" id="0"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBProxyObject" id="372490531"> + <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> + </object> + <object class="IBProxyObject" id="975951072"> + <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> + </object> + <object class="IBUIView" id="191373211"> + <reference key="NSNextResponder"/> + <int key="NSvFlags">292</int> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview"/> + <object class="NSColor" key="IBUIBackgroundColor"> + <int key="NSColorSpace">3</int> + <bytes key="NSWhite">MQA</bytes> + <object class="NSColorSpace" key="NSCustomColorSpace"> + <int key="NSID">2</int> + </object> + </object> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + </object> + <object class="IBObjectContainer" key="IBDocument.Objects"> + <object class="NSMutableArray" key="connectionRecords"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">view</string> + <reference key="source" ref="372490531"/> + <reference key="destination" ref="191373211"/> + </object> + <int key="connectionID">3</int> + </object> + </object> + <object class="IBMutableOrderedSet" key="objectRecords"> + <object class="NSArray" key="orderedObjects"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBObjectRecord"> + <int key="objectID">0</int> + <reference key="object" ref="0"/> + <reference key="children" ref="1000"/> + <nil key="parent"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">1</int> + <reference key="object" ref="191373211"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-1</int> + <reference key="object" ref="372490531"/> + <reference key="parent" ref="0"/> + <string key="objectName">File's Owner</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-2</int> + <reference key="object" ref="975951072"/> + <reference key="parent" ref="0"/> + </object> + </object> + </object> + <object class="NSMutableDictionary" key="flattenedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>-1.CustomClassName</string> + <string>-2.CustomClassName</string> + <string>1.IBEditorWindowLastContentRect</string> + <string>1.IBPluginDependency</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>HighScoresViewController</string> + <string>UIResponder</string> + <string>{{556, 412}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + </object> + <object class="NSMutableDictionary" key="unlocalizedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="activeLocalization"/> + <object class="NSMutableDictionary" key="localizations"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="sourceID"/> + <int key="maxID">3</int> + </object> + <object class="IBClassDescriber" key="IBDocument.Classes"> + <object class="NSMutableArray" key="referencedPartialClassDescriptions"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">HighScoresViewController</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">HighScoresViewController.h</string> + </object> + </object> + </object> + </object> + <int key="IBDocument.localizationMode">0</int> + <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> + <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> + <integer value="3000" key="NS.object.0"/> + </object> + <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> + <nil key="IBDocument.LastKnownRelativeProjectPath"/> + <int key="IBDocument.defaultPropertyAccessControl">3</int> + <string key="IBCocoaTouchPluginVersion">3.1</string> + </data> +</archive> diff --git a/Classes/OptionsViewController.h b/Classes/OptionsViewController.h new file mode 100644 index 0000000..f5a9b32 --- /dev/null +++ b/Classes/OptionsViewController.h @@ -0,0 +1,16 @@ +// +// OptionsViewController.h +// BalloonChallenge +// +// Created by Brian Wong on 2/9/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import <UIKit/UIKit.h> + + +@interface OptionsViewController : UIViewController { + +} + +@end diff --git a/Classes/OptionsViewController.m b/Classes/OptionsViewController.m new file mode 100644 index 0000000..c0f38d9 --- /dev/null +++ b/Classes/OptionsViewController.m @@ -0,0 +1,57 @@ +// +// OptionsViewController.m +// BalloonChallenge +// +// Created by Brian Wong on 2/9/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import "OptionsViewController.h" + + +@implementation OptionsViewController + +/* + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { + // Custom initialization + } + return self; +} +*/ + +/* +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} +*/ + +/* +// Override to allow orientations other than the default portrait orientation. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + // Return YES for supported orientations + return (interfaceOrientation == UIInterfaceOrientationPortrait); +} +*/ + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end diff --git a/Classes/OptionsViewController.xib b/Classes/OptionsViewController.xib new file mode 100644 index 0000000..ac1920b --- /dev/null +++ b/Classes/OptionsViewController.xib @@ -0,0 +1,150 @@ +<?xml version="1.0" encoding="UTF-8"?> +<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> + <data> + <int key="IBDocument.SystemTarget">784</int> + <string key="IBDocument.SystemVersion">10A394</string> + <string key="IBDocument.InterfaceBuilderVersion">732</string> + <string key="IBDocument.AppKitVersion">1027.1</string> + <string key="IBDocument.HIToolboxVersion">430.00</string> + <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> + <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string key="NS.object.0">60</string> + </object> + <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> + <bool key="EncodedWithXMLCoder">YES</bool> + <integer value="1"/> + </object> + <object class="NSArray" key="IBDocument.PluginDependencies"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + <object class="NSMutableDictionary" key="IBDocument.Metadata"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys" id="0"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBProxyObject" id="372490531"> + <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> + </object> + <object class="IBProxyObject" id="975951072"> + <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> + </object> + <object class="IBUIView" id="191373211"> + <reference key="NSNextResponder"/> + <int key="NSvFlags">292</int> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview"/> + <object class="NSColor" key="IBUIBackgroundColor"> + <int key="NSColorSpace">3</int> + <bytes key="NSWhite">MQA</bytes> + <object class="NSColorSpace" key="NSCustomColorSpace"> + <int key="NSID">2</int> + </object> + </object> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + </object> + <object class="IBObjectContainer" key="IBDocument.Objects"> + <object class="NSMutableArray" key="connectionRecords"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">view</string> + <reference key="source" ref="372490531"/> + <reference key="destination" ref="191373211"/> + </object> + <int key="connectionID">3</int> + </object> + </object> + <object class="IBMutableOrderedSet" key="objectRecords"> + <object class="NSArray" key="orderedObjects"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBObjectRecord"> + <int key="objectID">0</int> + <reference key="object" ref="0"/> + <reference key="children" ref="1000"/> + <nil key="parent"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">1</int> + <reference key="object" ref="191373211"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-1</int> + <reference key="object" ref="372490531"/> + <reference key="parent" ref="0"/> + <string key="objectName">File's Owner</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-2</int> + <reference key="object" ref="975951072"/> + <reference key="parent" ref="0"/> + </object> + </object> + </object> + <object class="NSMutableDictionary" key="flattenedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>-1.CustomClassName</string> + <string>-2.CustomClassName</string> + <string>1.IBEditorWindowLastContentRect</string> + <string>1.IBPluginDependency</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>OptionsViewController</string> + <string>UIResponder</string> + <string>{{556, 412}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + </object> + <object class="NSMutableDictionary" key="unlocalizedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="activeLocalization"/> + <object class="NSMutableDictionary" key="localizations"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="sourceID"/> + <int key="maxID">3</int> + </object> + <object class="IBClassDescriber" key="IBDocument.Classes"> + <object class="NSMutableArray" key="referencedPartialClassDescriptions"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">OptionsViewController</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">OptionsViewController.h</string> + </object> + </object> + </object> + </object> + <int key="IBDocument.localizationMode">0</int> + <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> + <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> + <integer value="3000" key="NS.object.0"/> + </object> + <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> + <nil key="IBDocument.LastKnownRelativeProjectPath"/> + <int key="IBDocument.defaultPropertyAccessControl">3</int> + <string key="IBCocoaTouchPluginVersion">3.1</string> + </data> +</archive> diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree index dd20f50..bfb9fc7 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree index 7864862..cab5da8 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree index 7dfc5e3..9e884d4 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree index 96d4812..387dd88 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header index 0d80187..1a2d9b4 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree index b7d0f1f..34227ed 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control index a23c2a5..29fdf6a 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings index 4a905d9..fca2b19 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree index dd34ee5..3609212 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols index 98df3dc..b478e7e 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols differ
bwong/BalloonChallenge
e634de3c4f7349994e40dbb5a4d2540d4ff4dda9
modified BalloonChallengeViewController to have 4 buttons and a bg image
diff --git a/BalloonChallengeViewController.xib b/BalloonChallengeViewController.xib index c8ed129..5671341 100644 --- a/BalloonChallengeViewController.xib +++ b/BalloonChallengeViewController.xib @@ -1,151 +1,501 @@ <?xml version="1.0" encoding="UTF-8"?> <archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> <data> <int key="IBDocument.SystemTarget">784</int> - <string key="IBDocument.SystemVersion">10A394</string> - <string key="IBDocument.InterfaceBuilderVersion">732</string> - <string key="IBDocument.AppKitVersion">1027.1</string> - <string key="IBDocument.HIToolboxVersion">430.00</string> + <string key="IBDocument.SystemVersion">10C540</string> + <string key="IBDocument.InterfaceBuilderVersion">740</string> + <string key="IBDocument.AppKitVersion">1038.25</string> + <string key="IBDocument.HIToolboxVersion">458.00</string> <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> - <string key="NS.object.0">60</string> + <string key="NS.object.0">62</string> </object> <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> <bool key="EncodedWithXMLCoder">YES</bool> <integer value="6"/> </object> <object class="NSArray" key="IBDocument.PluginDependencies"> <bool key="EncodedWithXMLCoder">YES</bool> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> </object> <object class="NSMutableDictionary" key="IBDocument.Metadata"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="NSArray" key="dict.sortedKeys" id="0"> <bool key="EncodedWithXMLCoder">YES</bool> </object> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> </object> </object> <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBProxyObject" id="372490531"> <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> </object> <object class="IBProxyObject" id="843779117"> <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> </object> <object class="IBUIView" id="774585933"> <reference key="NSNextResponder"/> <int key="NSvFlags">274</int> + <object class="NSMutableArray" key="NSSubviews"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBUIImageView" id="1015927794"> + <reference key="NSNextResponder" ref="774585933"/> + <int key="NSvFlags">274</int> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview" ref="774585933"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentMode">4</int> + <bool key="IBUIUserInteractionEnabled">NO</bool> + <object class="NSCustomResource" key="IBUIImage"> + <string key="NSClassName">NSImage</string> + <string key="NSResourceName">game_bg.png</string> + </object> + </object> + <object class="IBUIButton" id="879414223"> + <reference key="NSNextResponder" ref="774585933"/> + <int key="NSvFlags">292</int> + <string key="NSFrame">{{103, 150}, {113, 37}}</string> + <reference key="NSSuperview" ref="774585933"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentHorizontalAlignment">0</int> + <int key="IBUIContentVerticalAlignment">0</int> + <object class="NSFont" key="IBUIFont" id="954580566"> + <string key="NSName">Helvetica-Bold</string> + <double key="NSSize">15</double> + <int key="NSfFlags">16</int> + </object> + <int key="IBUIButtonType">1</int> + <string key="IBUINormalTitle">Play</string> + <object class="NSColor" key="IBUIHighlightedTitleColor" id="186910058"> + <int key="NSColorSpace">3</int> + <bytes key="NSWhite">MQA</bytes> + </object> + <object class="NSColor" key="IBUINormalTitleColor"> + <int key="NSColorSpace">1</int> + <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> + </object> + <object class="NSColor" key="IBUINormalTitleShadowColor" id="399200713"> + <int key="NSColorSpace">3</int> + <bytes key="NSWhite">MC41AA</bytes> + </object> + </object> + <object class="IBUIButton" id="315950724"> + <reference key="NSNextResponder" ref="774585933"/> + <int key="NSvFlags">292</int> + <string key="NSFrame">{{103, 195}, {113, 37}}</string> + <reference key="NSSuperview" ref="774585933"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentHorizontalAlignment">0</int> + <int key="IBUIContentVerticalAlignment">0</int> + <reference key="IBUIFont" ref="954580566"/> + <int key="IBUIButtonType">1</int> + <string key="IBUINormalTitle">Options</string> + <reference key="IBUIHighlightedTitleColor" ref="186910058"/> + <object class="NSColor" key="IBUINormalTitleColor"> + <int key="NSColorSpace">1</int> + <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> + </object> + <reference key="IBUINormalTitleShadowColor" ref="399200713"/> + </object> + <object class="IBUIButton" id="1039261273"> + <reference key="NSNextResponder" ref="774585933"/> + <int key="NSvFlags">292</int> + <string key="NSFrame">{{103, 285}, {113, 37}}</string> + <reference key="NSSuperview" ref="774585933"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentHorizontalAlignment">0</int> + <int key="IBUIContentVerticalAlignment">0</int> + <reference key="IBUIFont" ref="954580566"/> + <int key="IBUIButtonType">1</int> + <string key="IBUINormalTitle">Help</string> + <reference key="IBUIHighlightedTitleColor" ref="186910058"/> + <object class="NSColor" key="IBUINormalTitleColor"> + <int key="NSColorSpace">1</int> + <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> + </object> + <reference key="IBUINormalTitleShadowColor" ref="399200713"/> + </object> + <object class="IBUIButton" id="578362606"> + <reference key="NSNextResponder" ref="774585933"/> + <int key="NSvFlags">292</int> + <string key="NSFrame">{{103, 240}, {113, 37}}</string> + <reference key="NSSuperview" ref="774585933"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentHorizontalAlignment">0</int> + <int key="IBUIContentVerticalAlignment">0</int> + <reference key="IBUIFont" ref="954580566"/> + <int key="IBUIButtonType">1</int> + <string key="IBUINormalTitle">High Scores</string> + <reference key="IBUIHighlightedTitleColor" ref="186910058"/> + <object class="NSColor" key="IBUINormalTitleColor"> + <int key="NSColorSpace">1</int> + <bytes key="NSRGB">MC4xOTYwNzg0MyAwLjMwOTgwMzkzIDAuNTIxNTY4NjYAA</bytes> + </object> + <reference key="IBUINormalTitleShadowColor" ref="399200713"/> + </object> + </object> <string key="NSFrameSize">{320, 460}</string> <reference key="NSSuperview"/> <object class="NSColor" key="IBUIBackgroundColor"> <int key="NSColorSpace">3</int> <bytes key="NSWhite">MC43NQA</bytes> <object class="NSColorSpace" key="NSCustomColorSpace"> <int key="NSID">2</int> </object> </object> <bool key="IBUIClearsContextBeforeDrawing">NO</bool> <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> </object> </object> <object class="IBObjectContainer" key="IBDocument.Objects"> <object class="NSMutableArray" key="connectionRecords"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBConnectionRecord"> <object class="IBCocoaTouchOutletConnection" key="connection"> <string key="label">view</string> <reference key="source" ref="372490531"/> <reference key="destination" ref="774585933"/> </object> <int key="connectionID">7</int> </object> </object> <object class="IBMutableOrderedSet" key="objectRecords"> <object class="NSArray" key="orderedObjects"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBObjectRecord"> <int key="objectID">0</int> <reference key="object" ref="0"/> <reference key="children" ref="1000"/> <nil key="parent"/> </object> <object class="IBObjectRecord"> <int key="objectID">-1</int> <reference key="object" ref="372490531"/> <reference key="parent" ref="0"/> <string key="objectName">File's Owner</string> </object> <object class="IBObjectRecord"> <int key="objectID">-2</int> <reference key="object" ref="843779117"/> <reference key="parent" ref="0"/> </object> <object class="IBObjectRecord"> <int key="objectID">6</int> <reference key="object" ref="774585933"/> + <object class="NSMutableArray" key="children"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference ref="1015927794"/> + <reference ref="879414223"/> + <reference ref="315950724"/> + <reference ref="578362606"/> + <reference ref="1039261273"/> + </object> <reference key="parent" ref="0"/> </object> + <object class="IBObjectRecord"> + <int key="objectID">8</int> + <reference key="object" ref="1015927794"/> + <reference key="parent" ref="774585933"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">9</int> + <reference key="object" ref="879414223"/> + <reference key="parent" ref="774585933"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">10</int> + <reference key="object" ref="315950724"/> + <reference key="parent" ref="774585933"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">11</int> + <reference key="object" ref="1039261273"/> + <reference key="parent" ref="774585933"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">12</int> + <reference key="object" ref="578362606"/> + <reference key="parent" ref="774585933"/> + </object> </object> </object> <object class="NSMutableDictionary" key="flattenedProperties"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="NSArray" key="dict.sortedKeys"> <bool key="EncodedWithXMLCoder">YES</bool> <string>-1.CustomClassName</string> <string>-2.CustomClassName</string> + <string>10.IBPluginDependency</string> + <string>11.IBPluginDependency</string> + <string>12.IBPluginDependency</string> <string>6.IBEditorWindowLastContentRect</string> <string>6.IBPluginDependency</string> + <string>8.IBPluginDependency</string> + <string>9.IBPluginDependency</string> </object> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> <string>BalloonChallengeViewController</string> <string>UIResponder</string> - <string>{{438, 347}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>{{438, 276}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> </object> </object> <object class="NSMutableDictionary" key="unlocalizedProperties"> <bool key="EncodedWithXMLCoder">YES</bool> <reference key="dict.sortedKeys" ref="0"/> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> </object> </object> <nil key="activeLocalization"/> <object class="NSMutableDictionary" key="localizations"> <bool key="EncodedWithXMLCoder">YES</bool> <reference key="dict.sortedKeys" ref="0"/> <object class="NSMutableArray" key="dict.values"> <bool key="EncodedWithXMLCoder">YES</bool> </object> </object> <nil key="sourceID"/> - <int key="maxID">7</int> + <int key="maxID">12</int> </object> <object class="IBClassDescriber" key="IBDocument.Classes"> <object class="NSMutableArray" key="referencedPartialClassDescriptions"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBPartialClassDescription"> <string key="className">BalloonChallengeViewController</string> <string key="superclassName">UIViewController</string> <object class="IBClassDescriptionSource" key="sourceIdentifier"> <string key="majorKey">IBProjectSource</string> <string key="minorKey">Classes/BalloonChallengeViewController.h</string> </object> </object> </object> + <object class="NSMutableArray" key="referencedPartialClassDescriptionsV3.2+"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSError.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSFileManager.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyValueCoding.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyValueObserving.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyedArchiver.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSNetServices.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSObject.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSPort.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSRunLoop.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSStream.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSThread.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSURL.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSURLConnection.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSXMLParser.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIAccessibility.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UINibLoading.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier" id="713855212"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIResponder.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIButton</string> + <string key="superclassName">UIControl</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIButton.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIControl</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIControl.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIImageView</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIImageView.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIResponder</string> + <string key="superclassName">NSObject</string> + <reference key="sourceIdentifier" ref="713855212"/> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UISearchBar</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UISearchBar.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UISearchDisplayController</string> + <string key="superclassName">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UISearchDisplayController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UITextField.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIView</string> + <string key="superclassName">UIResponder</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIView.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UINavigationController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UITabBarController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <string key="superclassName">UIResponder</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIViewController.h</string> + </object> + </object> + </object> </object> <int key="IBDocument.localizationMode">0</int> <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> <integer value="3100" key="NS.object.0"/> </object> <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> <string key="IBDocument.LastKnownRelativeProjectPath">BalloonChallenge.xcodeproj</string> <int key="IBDocument.defaultPropertyAccessControl">3</int> <string key="IBCocoaTouchPluginVersion">3.1</string> </data> </archive>
bwong/BalloonChallenge
9a474976fedac92cce40cd4e0bd75f94eb5e3b39
added a game view with a background picture
diff --git a/BalloonChallenge.xcodeproj/project.pbxproj b/BalloonChallenge.xcodeproj/project.pbxproj index 6c7a4a5..dba0e70 100755 --- a/BalloonChallenge.xcodeproj/project.pbxproj +++ b/BalloonChallenge.xcodeproj/project.pbxproj @@ -1,249 +1,263 @@ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 45; objects = { /* Begin PBXBuildFile section */ + 0A24545211213B88009A536A /* GameView.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A24545011213B88009A536A /* GameView.m */; }; + 0A24545311213B88009A536A /* GameView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0A24545111213B88009A536A /* GameView.xib */; }; + 0A24546911214737009A536A /* game_bg.png in Resources */ = {isa = PBXBuildFile; fileRef = 0A24546811214737009A536A /* game_bg.png */; }; 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; }; 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; }; 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */; }; 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 28AD733E0D9D9553002E5188 /* MainWindow.xib */; }; 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 0A24544F11213B88009A536A /* GameView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameView.h; sourceTree = "<group>"; }; + 0A24545011213B88009A536A /* GameView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GameView.m; sourceTree = "<group>"; }; + 0A24545111213B88009A536A /* GameView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = GameView.xib; path = Classes/GameView.xib; sourceTree = "<group>"; }; + 0A24546811214737009A536A /* game_bg.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = game_bg.png; sourceTree = "<group>"; }; 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeAppDelegate.h; sourceTree = "<group>"; }; 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeAppDelegate.m; sourceTree = "<group>"; }; 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BalloonChallenge.app; sourceTree = BUILT_PRODUCTS_DIR; }; 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = BalloonChallengeViewController.xib; sourceTree = "<group>"; }; 28AD733E0D9D9553002E5188 /* MainWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MainWindow.xib; sourceTree = "<group>"; }; 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeViewController.h; sourceTree = "<group>"; }; 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeViewController.m; sourceTree = "<group>"; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallenge_Prefix.pch; sourceTree = "<group>"; }; 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "BalloonChallenge-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 080E96DDFE201D6D7F000001 /* Classes */ = { isa = PBXGroup; children = ( 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */, 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */, 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */, 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */, + 0A24544F11213B88009A536A /* GameView.h */, + 0A24545011213B88009A536A /* GameView.m */, ); path = Classes; sourceTree = "<group>"; }; 19C28FACFE9D520D11CA2CBB /* Products */ = { isa = PBXGroup; children = ( 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */, ); name = Products; sourceTree = "<group>"; }; 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { isa = PBXGroup; children = ( 080E96DDFE201D6D7F000001 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, 29B97317FDCFA39411CA2CEA /* Resources */, 29B97323FDCFA39411CA2CEA /* Frameworks */, 19C28FACFE9D520D11CA2CBB /* Products */, ); name = CustomTemplate; sourceTree = "<group>"; }; 29B97315FDCFA39411CA2CEA /* Other Sources */ = { isa = PBXGroup; children = ( 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */, 29B97316FDCFA39411CA2CEA /* main.m */, ); name = "Other Sources"; sourceTree = "<group>"; }; 29B97317FDCFA39411CA2CEA /* Resources */ = { isa = PBXGroup; children = ( + 0A24546811214737009A536A /* game_bg.png */, + 0A24545111213B88009A536A /* GameView.xib */, 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */, 28AD733E0D9D9553002E5188 /* MainWindow.xib */, 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */, ); name = Resources; sourceTree = "<group>"; }; 29B97323FDCFA39411CA2CEA /* Frameworks */ = { isa = PBXGroup; children = ( 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, 1D30AB110D05D00D00671497 /* Foundation.framework */, 288765A40DF7441C002DB57D /* CoreGraphics.framework */, ); name = Frameworks; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { isa = PBXNativeTarget; buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */; buildPhases = ( 1D60588D0D05DD3D006BFB54 /* Resources */, 1D60588E0D05DD3D006BFB54 /* Sources */, 1D60588F0D05DD3D006BFB54 /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = BalloonChallenge; productName = BalloonChallenge; productReference = 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */; compatibilityVersion = "Xcode 3.1"; hasScannedForEncodings = 1; mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; projectDirPath = ""; projectRoot = ""; targets = ( 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 1D60588D0D05DD3D006BFB54 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */, 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */, + 0A24545311213B88009A536A /* GameView.xib in Resources */, + 0A24546911214737009A536A /* game_bg.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 1D60588E0D05DD3D006BFB54 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 1D60589B0D05DD56006BFB54 /* main.m in Sources */, 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */, 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */, + 0A24545211213B88009A536A /* GameView.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 1D6058940D05DD3E006BFB54 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Debug; }; 1D6058950D05DD3E006BFB54 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; INFOPLIST_FILE = "BalloonChallenge-Info.plist"; PRODUCT_NAME = BalloonChallenge; }; name = Release; }; C01FCF4F08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Debug; }; C01FCF5008A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = iphoneos3.1.2; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( 1D6058940D05DD3E006BFB54 /* Debug */, 1D6058950D05DD3E006BFB54 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */ = { isa = XCConfigurationList; buildConfigurations = ( C01FCF4F08A954540054247B /* Debug */, C01FCF5008A954540054247B /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; } diff --git a/Classes/GameView.h b/Classes/GameView.h new file mode 100644 index 0000000..83e9282 --- /dev/null +++ b/Classes/GameView.h @@ -0,0 +1,16 @@ +// +// GameView.h +// BalloonChallenge +// +// Created by Kevin Weiler on 2/8/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import <UIKit/UIKit.h> + + +@interface GameView : UIViewController { + +} + +@end diff --git a/Classes/GameView.m b/Classes/GameView.m new file mode 100644 index 0000000..679fa4b --- /dev/null +++ b/Classes/GameView.m @@ -0,0 +1,57 @@ +// +// GameView.m +// BalloonChallenge +// +// Created by Kevin Weiler on 2/8/10. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import "GameView.h" + + +@implementation GameView + +/* + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { + // Custom initialization + } + return self; +} +*/ + +/* +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} +*/ + +/* +// Override to allow orientations other than the default portrait orientation. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + // Return YES for supported orientations + return (interfaceOrientation == UIInterfaceOrientationPortrait); +} +*/ + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end diff --git a/Classes/GameView.xib b/Classes/GameView.xib new file mode 100644 index 0000000..96639c2 --- /dev/null +++ b/Classes/GameView.xib @@ -0,0 +1,366 @@ +<?xml version="1.0" encoding="UTF-8"?> +<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> + <data> + <int key="IBDocument.SystemTarget">784</int> + <string key="IBDocument.SystemVersion">10C540</string> + <string key="IBDocument.InterfaceBuilderVersion">740</string> + <string key="IBDocument.AppKitVersion">1038.25</string> + <string key="IBDocument.HIToolboxVersion">458.00</string> + <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> + <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string key="NS.object.0">62</string> + </object> + <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> + <bool key="EncodedWithXMLCoder">YES</bool> + <integer value="4"/> + </object> + <object class="NSArray" key="IBDocument.PluginDependencies"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + <object class="NSMutableDictionary" key="IBDocument.Metadata"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys" id="0"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBProxyObject" id="372490531"> + <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> + </object> + <object class="IBProxyObject" id="975951072"> + <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> + </object> + <object class="IBUIView" id="191373211"> + <reference key="NSNextResponder"/> + <int key="NSvFlags">292</int> + <object class="NSMutableArray" key="NSSubviews"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBUIImageView" id="739462147"> + <reference key="NSNextResponder" ref="191373211"/> + <int key="NSvFlags">274</int> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview" ref="191373211"/> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <int key="IBUIContentMode">2</int> + <bool key="IBUIUserInteractionEnabled">NO</bool> + <object class="NSCustomResource" key="IBUIImage"> + <string key="NSClassName">NSImage</string> + <string key="NSResourceName">game_bg.png</string> + </object> + </object> + </object> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview"/> + <object class="NSColor" key="IBUIBackgroundColor"> + <int key="NSColorSpace">3</int> + <bytes key="NSWhite">MQA</bytes> + <object class="NSColorSpace" key="NSCustomColorSpace"> + <int key="NSID">2</int> + </object> + </object> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + </object> + <object class="IBObjectContainer" key="IBDocument.Objects"> + <object class="NSMutableArray" key="connectionRecords"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">view</string> + <reference key="source" ref="372490531"/> + <reference key="destination" ref="191373211"/> + </object> + <int key="connectionID">3</int> + </object> + </object> + <object class="IBMutableOrderedSet" key="objectRecords"> + <object class="NSArray" key="orderedObjects"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBObjectRecord"> + <int key="objectID">0</int> + <reference key="object" ref="0"/> + <reference key="children" ref="1000"/> + <nil key="parent"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">1</int> + <reference key="object" ref="191373211"/> + <object class="NSMutableArray" key="children"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference ref="739462147"/> + </object> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-1</int> + <reference key="object" ref="372490531"/> + <reference key="parent" ref="0"/> + <string key="objectName">File's Owner</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-2</int> + <reference key="object" ref="975951072"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">4</int> + <reference key="object" ref="739462147"/> + <reference key="parent" ref="191373211"/> + </object> + </object> + </object> + <object class="NSMutableDictionary" key="flattenedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>-1.CustomClassName</string> + <string>-2.CustomClassName</string> + <string>1.IBEditorWindowLastContentRect</string> + <string>1.IBPluginDependency</string> + <string>4.IBPluginDependency</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>GameView</string> + <string>UIResponder</string> + <string>{{430, 144}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + </object> + <object class="NSMutableDictionary" key="unlocalizedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="activeLocalization"/> + <object class="NSMutableDictionary" key="localizations"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="sourceID"/> + <int key="maxID">4</int> + </object> + <object class="IBClassDescriber" key="IBDocument.Classes"> + <object class="NSMutableArray" key="referencedPartialClassDescriptions"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">GameView</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">Classes/GameView.h</string> + </object> + </object> + </object> + <object class="NSMutableArray" key="referencedPartialClassDescriptionsV3.2+"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSError.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSFileManager.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyValueCoding.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyValueObserving.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSKeyedArchiver.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSNetServices.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSObject.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSPort.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSRunLoop.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSStream.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSThread.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSURL.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSURLConnection.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">Foundation.framework/Headers/NSXMLParser.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIAccessibility.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UINibLoading.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier" id="543548073"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIResponder.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIImageView</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIImageView.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIResponder</string> + <string key="superclassName">NSObject</string> + <reference key="sourceIdentifier" ref="543548073"/> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UISearchBar</string> + <string key="superclassName">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UISearchBar.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UISearchDisplayController</string> + <string key="superclassName">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UISearchDisplayController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIView</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UITextField.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIView</string> + <string key="superclassName">UIResponder</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIView.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UINavigationController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UITabBarController.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">UIViewController</string> + <string key="superclassName">UIResponder</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBFrameworkSource</string> + <string key="minorKey">UIKit.framework/Headers/UIViewController.h</string> + </object> + </object> + </object> + </object> + <int key="IBDocument.localizationMode">0</int> + <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> + <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> + <integer value="3000" key="NS.object.0"/> + </object> + <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> + <string key="IBDocument.LastKnownRelativeProjectPath">../BalloonChallenge.xcodeproj</string> + <int key="IBDocument.defaultPropertyAccessControl">3</int> + <string key="IBCocoaTouchPluginVersion">3.1</string> + </data> +</archive> diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree index 865cfd4..dd20f50 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree index 538e82a..7864862 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree index 36dfbae..7dfc5e3 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree index b49009e..96d4812 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header index 1a0a2a6..0d80187 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree index a9fa23f..b7d0f1f 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control index 99b3547..a23c2a5 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings index 370a045..4a905d9 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree index 62d1c29..dd34ee5 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols index abc6789..98df3dc 100644 Binary files a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols differ diff --git a/game_bg.png b/game_bg.png new file mode 100644 index 0000000..166c0c9 Binary files /dev/null and b/game_bg.png differ
bwong/BalloonChallenge
6052cd8dffbb30c677112a6858e4ac13cced60f6
make new project in xcode
diff --git a/BalloonChallenge-Info.plist b/BalloonChallenge-Info.plist new file mode 100644 index 0000000..3289444 --- /dev/null +++ b/BalloonChallenge-Info.plist @@ -0,0 +1,30 @@ +<?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>CFBundleDisplayName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundleExecutable</key> + <string>${EXECUTABLE_NAME}</string> + <key>CFBundleIconFile</key> + <string></string> + <key>CFBundleIdentifier</key> + <string>com.yourcompany.${PRODUCT_NAME:rfc1034identifier}</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>1.0</string> + <key>LSRequiresIPhoneOS</key> + <true/> + <key>NSMainNibFile</key> + <string>MainWindow</string> +</dict> +</plist> diff --git a/BalloonChallenge.xcodeproj/bwong.mode1v3 b/BalloonChallenge.xcodeproj/bwong.mode1v3 new file mode 100644 index 0000000..7a4599c --- /dev/null +++ b/BalloonChallenge.xcodeproj/bwong.mode1v3 @@ -0,0 +1,1357 @@ +<?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>ActivePerspectiveName</key> + <string>Project</string> + <key>AllowedModules</key> + <array> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Name</key> + <string>Groups and Files Outline View</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Name</key> + <string>Editor</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCTaskListModule</string> + <key>Name</key> + <string>Task List</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCDetailModule</string> + <key>Name</key> + <string>File and Smart Group Detail Viewer</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXBuildResultsModule</string> + <key>Name</key> + <string>Detailed Build Results Viewer</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXProjectFindModule</string> + <key>Name</key> + <string>Project Batch Find Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCProjectFormatConflictsModule</string> + <key>Name</key> + <string>Project Format Conflicts List</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXBookmarksModule</string> + <key>Name</key> + <string>Bookmarks Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXClassBrowserModule</string> + <key>Name</key> + <string>Class Browser</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXCVSModule</string> + <key>Name</key> + <string>Source Code Control Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXDebugBreakpointsModule</string> + <key>Name</key> + <string>Debug Breakpoints Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCDockableInspector</string> + <key>Name</key> + <string>Inspector</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>PBXOpenQuicklyModule</string> + <key>Name</key> + <string>Open Quickly Tool</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXDebugSessionModule</string> + <key>Name</key> + <string>Debugger</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>1</string> + <key>Module</key> + <string>PBXDebugCLIModule</string> + <key>Name</key> + <string>Debug Console</string> + </dict> + <dict> + <key>BundleLoadPath</key> + <string></string> + <key>MaxInstances</key> + <string>n</string> + <key>Module</key> + <string>XCSnapshotModule</string> + <key>Name</key> + <string>Snapshots Tool</string> + </dict> + </array> + <key>BundlePath</key> + <string>/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources</string> + <key>Description</key> + <string>DefaultDescriptionKey</string> + <key>DockingSystemVisible</key> + <false/> + <key>Extension</key> + <string>mode1v3</string> + <key>FavBarConfig</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1D6E99AE111D83EB00661416</string> + <key>XCBarModuleItemNames</key> + <dict/> + <key>XCBarModuleItems</key> + <array/> + </dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>com.apple.perspectives.project.mode1v3</string> + <key>MajorVersion</key> + <integer>33</integer> + <key>MinorVersion</key> + <integer>0</integer> + <key>Name</key> + <string>Default</string> + <key>Notifications</key> + <array/> + <key>OpenEditors</key> + <array/> + <key>PerspectiveWidths</key> + <array> + <integer>-1</integer> + <integer>-1</integer> + </array> + <key>Perspectives</key> + <array> + <dict> + <key>ChosenToolbarItems</key> + <array> + <string>active-combo-popup</string> + <string>action</string> + <string>NSToolbarFlexibleSpaceItem</string> + <string>debugger-enable-breakpoints</string> + <string>build-and-go</string> + <string>com.apple.ide.PBXToolbarStopButton</string> + <string>get-info</string> + <string>NSToolbarFlexibleSpaceItem</string> + <string>com.apple.pbx.toolbar.searchfield</string> + </array> + <key>ControllerClassBaseName</key> + <string></string> + <key>IconName</key> + <string>WindowOfProjectWithEditor</string> + <key>Identifier</key> + <string>perspective.project</string> + <key>IsVertical</key> + <false/> + <key>Layout</key> + <array> + <dict> + <key>BecomeActive</key> + <true/> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C37FBAC04509CD000000102</string> + <string>1C37FAAC04509CD000000102</string> + <string>1C37FABC05509CD000000102</string> + <string>1C37FABC05539CD112110102</string> + <string>E2644B35053B69B200211256</string> + <string>1C37FABC04509CD000100104</string> + <string>1CC0EA4004350EF90044410B</string> + <string>1CC0EA4004350EF90041110B</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>1CE0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>yes</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>186</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>29B97314FDCFA39411CA2CEA</string> + <string>1C37FABC05509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {186, 445}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <true/> + <key>XCSharingToken</key> + <string>com.apple.Xcode.GFSharingToken</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {203, 463}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>186</real> + </array> + <key>RubberWindowFrame</key> + <string>267 211 788 504 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>203pt</string> + </dict> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20306471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>MyNewFile14.java</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20406471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>MyNewFile14.java</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <true/> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {580, 277}}</string> + <key>RubberWindowFrame</key> + <string>267 211 788 504 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>277pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CE0B20506471E060097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Detail</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 282}, {580, 181}}</string> + <key>RubberWindowFrame</key> + <string>267 211 788 504 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>XCDetailModule</string> + <key>Proportion</key> + <string>181pt</string> + </dict> + </array> + <key>Proportion</key> + <string>580pt</string> + </dict> + </array> + <key>Name</key> + <string>Project</string> + <key>ServiceClasses</key> + <array> + <string>XCModuleDock</string> + <string>PBXSmartGroupTreeModule</string> + <string>XCModuleDock</string> + <string>PBXNavigatorGroup</string> + <string>XCDetailModule</string> + </array> + <key>TableOfContents</key> + <array> + <string>1D6E99AC111D83EB00661416</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1D6E99AD111D83EB00661416</string> + <string>1CE0B20306471E060097A5F4</string> + <string>1CE0B20506471E060097A5F4</string> + </array> + <key>ToolbarConfigUserDefaultsMinorVersion</key> + <string>2</string> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.defaultV3</string> + </dict> + <dict> + <key>ControllerClassBaseName</key> + <string></string> + <key>IconName</key> + <string>WindowOfProject</string> + <key>Identifier</key> + <string>perspective.morph</string> + <key>IsVertical</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C37FBAC04509CD000000102</string> + <string>1C37FAAC04509CD000000102</string> + <string>1C08E77C0454961000C914BD</string> + <string>1C37FABC05509CD000000102</string> + <string>1C37FABC05539CD112110102</string> + <string>E2644B35053B69B200211256</string> + <string>1C37FABC04509CD000100104</string> + <string>1CC0EA4004350EF90044410B</string> + <string>1CC0EA4004350EF90041110B</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>11E0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>yes</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>186</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>29B97314FDCFA39411CA2CEA</string> + <string>1C37FABC05509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {186, 337}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <integer>1</integer> + <key>XCSharingToken</key> + <string>com.apple.Xcode.GFSharingToken</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {203, 355}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>186</real> + </array> + <key>RubberWindowFrame</key> + <string>373 269 690 397 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Morph</string> + <key>PreferredWidth</key> + <integer>300</integer> + <key>ServiceClasses</key> + <array> + <string>XCModuleDock</string> + <string>PBXSmartGroupTreeModule</string> + </array> + <key>TableOfContents</key> + <array> + <string>11E0B1FE06471DED0097A5F4</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.default.shortV3</string> + </dict> + </array> + <key>PerspectivesBarVisible</key> + <false/> + <key>ShelfIsVisible</key> + <false/> + <key>SourceDescription</key> + <string>file at '/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources/XCPerspectivesSpecificationMode1.xcperspec'</string> + <key>StatusbarIsVisible</key> + <true/> + <key>TimeStamp</key> + <real>0.0</real> + <key>ToolbarConfigUserDefaultsMinorVersion</key> + <string>2</string> + <key>ToolbarDisplayMode</key> + <integer>1</integer> + <key>ToolbarIsVisible</key> + <true/> + <key>ToolbarSizeMode</key> + <integer>1</integer> + <key>Type</key> + <string>Perspectives</string> + <key>UpdateMessage</key> + <string>The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'?</string> + <key>WindowJustification</key> + <integer>5</integer> + <key>WindowOrderList</key> + <array> + <string>1D6E99AF111D83EB00661416</string> + <string>/Users/bwong/Documents/COEN296/BalloonChallenge/BalloonChallenge.xcodeproj</string> + </array> + <key>WindowString</key> + <string>267 211 788 504 0 0 1280 778 </string> + <key>WindowToolsV3</key> + <array> + <dict> + <key>FirstTimeWindowDisplayed</key> + <false/> + <key>Identifier</key> + <string>windowTool.build</string> + <key>IsVertical</key> + <true/> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528F0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string></string> + <key>StatusBarVisibility</key> + <true/> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {500, 218}}</string> + <key>RubberWindowFrame</key> + <string>288 192 500 500 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>218pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>XCMainBuildResultsModuleGUID</string> + <key>PBXProjectModuleLabel</key> + <string>Build Results</string> + <key>XCBuildResultsTrigger_Collapse</key> + <integer>1021</integer> + <key>XCBuildResultsTrigger_Open</key> + <integer>1011</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 223}, {500, 236}}</string> + <key>RubberWindowFrame</key> + <string>288 192 500 500 0 0 1280 778 </string> + </dict> + <key>Module</key> + <string>PBXBuildResultsModule</string> + <key>Proportion</key> + <string>236pt</string> + </dict> + </array> + <key>Proportion</key> + <string>459pt</string> + </dict> + </array> + <key>Name</key> + <string>Build Results</string> + <key>ServiceClasses</key> + <array> + <string>PBXBuildResultsModule</string> + </array> + <key>StatusbarIsVisible</key> + <true/> + <key>TableOfContents</key> + <array> + <string>1D6E99AF111D83EB00661416</string> + <string>1D6E99B0111D83EB00661416</string> + <string>1CD0528F0623707200166675</string> + <string>XCMainBuildResultsModuleGUID</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.buildV3</string> + <key>WindowContentMinSize</key> + <string>486 300</string> + <key>WindowString</key> + <string>288 192 500 500 0 0 1280 778 </string> + <key>WindowToolGUID</key> + <string>1D6E99AF111D83EB00661416</string> + <key>WindowToolIsVisible</key> + <false/> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debugger</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>Debugger</key> + <dict> + <key>HorizontalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {317, 164}}</string> + <string>{{317, 0}, {377, 164}}</string> + </array> + </dict> + <key>VerticalSplitView</key> + <dict> + <key>_collapsingFrameDimension</key> + <real>0.0</real> + <key>_indexOfCollapsedView</key> + <integer>0</integer> + <key>_percentageOfCollapsedView</key> + <real>0.0</real> + <key>isCollapsed</key> + <string>yes</string> + <key>sizes</key> + <array> + <string>{{0, 0}, {694, 164}}</string> + <string>{{0, 164}, {694, 216}}</string> + </array> + </dict> + </dict> + <key>LauncherConfigVersion</key> + <string>8</string> + <key>PBXProjectModuleGUID</key> + <string>1C162984064C10D400B95A72</string> + <key>PBXProjectModuleLabel</key> + <string>Debug - GLUTExamples (Underwater)</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>DebugConsoleDrawerSize</key> + <string>{100, 120}</string> + <key>DebugConsoleVisible</key> + <string>None</string> + <key>DebugConsoleWindowFrame</key> + <string>{{200, 200}, {500, 300}}</string> + <key>DebugSTDIOWindowFrame</key> + <string>{{200, 200}, {500, 300}}</string> + <key>Frame</key> + <string>{{0, 0}, {694, 380}}</string> + <key>RubberWindowFrame</key> + <string>321 238 694 422 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXDebugSessionModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Debugger</string> + <key>ServiceClasses</key> + <array> + <string>PBXDebugSessionModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1CD10A99069EF8BA00B06720</string> + <string>1C0AD2AB069F1E9B00FABCE6</string> + <string>1C162984064C10D400B95A72</string> + <string>1C0AD2AC069F1E9B00FABCE6</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.debugV3</string> + <key>WindowString</key> + <string>321 238 694 422 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1CD10A99069EF8BA00B06720</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.find</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CDD528C0622207200134675</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528D0623707200166675</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {781, 167}}</string> + <key>RubberWindowFrame</key> + <string>62 385 781 470 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>781pt</string> + </dict> + </array> + <key>Proportion</key> + <string>50%</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD0528E0623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>Project Find</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{8, 0}, {773, 254}}</string> + <key>RubberWindowFrame</key> + <string>62 385 781 470 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXProjectFindModule</string> + <key>Proportion</key> + <string>50%</string> + </dict> + </array> + <key>Proportion</key> + <string>428pt</string> + </dict> + </array> + <key>Name</key> + <string>Project Find</string> + <key>ServiceClasses</key> + <array> + <string>PBXProjectFindModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C530D57069F1CE1000CFCEE</string> + <string>1C530D58069F1CE1000CFCEE</string> + <string>1C530D59069F1CE1000CFCEE</string> + <string>1CDD528C0622207200134675</string> + <string>1C530D5A069F1CE1000CFCEE</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1CD0528E0623707200166675</string> + </array> + <key>WindowString</key> + <string>62 385 781 470 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1C530D57069F1CE1000CFCEE</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>MENUSEPARATOR</string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debuggerConsole</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAAC065D492600B07095</string> + <key>PBXProjectModuleLabel</key> + <string>Debugger Console</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {650, 250}}</string> + <key>RubberWindowFrame</key> + <string>516 632 650 250 0 0 1680 1027 </string> + </dict> + <key>Module</key> + <string>PBXDebugCLIModule</string> + <key>Proportion</key> + <string>209pt</string> + </dict> + </array> + <key>Proportion</key> + <string>209pt</string> + </dict> + </array> + <key>Name</key> + <string>Debugger Console</string> + <key>ServiceClasses</key> + <array> + <string>PBXDebugCLIModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C78EAAD065D492600B07095</string> + <string>1C78EAAE065D492600B07095</string> + <string>1C78EAAC065D492600B07095</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.consoleV3</string> + <key>WindowString</key> + <string>650 41 650 250 0 0 1280 1002 </string> + <key>WindowToolGUID</key> + <string>1C78EAAD065D492600B07095</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.snapshots</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>XCSnapshotModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Snapshots</string> + <key>ServiceClasses</key> + <array> + <string>XCSnapshotModule</string> + </array> + <key>StatusbarIsVisible</key> + <string>Yes</string> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.snapshots</string> + <key>WindowString</key> + <string>315 824 300 550 0 0 1440 878 </string> + <key>WindowToolIsVisible</key> + <string>Yes</string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.scm</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAB2065D492600B07095</string> + <key>PBXProjectModuleLabel</key> + <string>&lt;No Editor&gt;</string> + <key>PBXSplitModuleInNavigatorKey</key> + <dict> + <key>Split0</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1C78EAB3065D492600B07095</string> + </dict> + <key>SplitCount</key> + <string>1</string> + </dict> + <key>StatusBarVisibility</key> + <integer>1</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {452, 0}}</string> + <key>RubberWindowFrame</key> + <string>743 379 452 308 0 0 1280 1002 </string> + </dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>0pt</string> + </dict> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CD052920623707200166675</string> + <key>PBXProjectModuleLabel</key> + <string>SCM</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>ConsoleFrame</key> + <string>{{0, 259}, {452, 0}}</string> + <key>Frame</key> + <string>{{0, 7}, {452, 259}}</string> + <key>RubberWindowFrame</key> + <string>743 379 452 308 0 0 1280 1002 </string> + <key>TableConfiguration</key> + <array> + <string>Status</string> + <real>30</real> + <string>FileName</string> + <real>199</real> + <string>Path</string> + <real>197.0950012207031</real> + </array> + <key>TableFrame</key> + <string>{{0, 0}, {452, 250}}</string> + </dict> + <key>Module</key> + <string>PBXCVSModule</string> + <key>Proportion</key> + <string>262pt</string> + </dict> + </array> + <key>Proportion</key> + <string>266pt</string> + </dict> + </array> + <key>Name</key> + <string>SCM</string> + <key>ServiceClasses</key> + <array> + <string>PBXCVSModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1C78EAB4065D492600B07095</string> + <string>1C78EAB5065D492600B07095</string> + <string>1C78EAB2065D492600B07095</string> + <string>1CD052920623707200166675</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.scm</string> + <key>WindowString</key> + <string>743 379 452 308 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.breakpoints</string> + <key>IsVertical</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>PBXBottomSmartGroupGIDs</key> + <array> + <string>1C77FABC04509CD000000102</string> + </array> + <key>PBXProjectModuleGUID</key> + <string>1CE0B1FE06471DED0097A5F4</string> + <key>PBXProjectModuleLabel</key> + <string>Files</string> + <key>PBXProjectStructureProvided</key> + <string>no</string> + <key>PBXSmartGroupTreeModuleColumnData</key> + <dict> + <key>PBXSmartGroupTreeModuleColumnWidthsKey</key> + <array> + <real>168</real> + </array> + <key>PBXSmartGroupTreeModuleColumnsKey_v4</key> + <array> + <string>MainColumn</string> + </array> + </dict> + <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key> + <dict> + <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key> + <array> + <string>1C77FABC04509CD000000102</string> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key> + <array> + <array> + <integer>0</integer> + </array> + </array> + <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key> + <string>{{0, 0}, {168, 350}}</string> + </dict> + <key>PBXTopSmartGroupGIDs</key> + <array/> + <key>XCIncludePerspectivesSwitch</key> + <integer>0</integer> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{0, 0}, {185, 368}}</string> + <key>GroupTreeTableConfiguration</key> + <array> + <string>MainColumn</string> + <real>168</real> + </array> + <key>RubberWindowFrame</key> + <string>315 424 744 409 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXSmartGroupTreeModule</string> + <key>Proportion</key> + <string>185pt</string> + </dict> + <dict> + <key>ContentConfiguration</key> + <dict> + <key>PBXProjectModuleGUID</key> + <string>1CA1AED706398EBD00589147</string> + <key>PBXProjectModuleLabel</key> + <string>Detail</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{{190, 0}, {554, 368}}</string> + <key>RubberWindowFrame</key> + <string>315 424 744 409 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>XCDetailModule</string> + <key>Proportion</key> + <string>554pt</string> + </dict> + </array> + <key>Proportion</key> + <string>368pt</string> + </dict> + </array> + <key>MajorVersion</key> + <integer>3</integer> + <key>MinorVersion</key> + <integer>0</integer> + <key>Name</key> + <string>Breakpoints</string> + <key>ServiceClasses</key> + <array> + <string>PBXSmartGroupTreeModule</string> + <string>XCDetailModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>TableOfContents</key> + <array> + <string>1CDDB66807F98D9800BB5817</string> + <string>1CDDB66907F98D9800BB5817</string> + <string>1CE0B1FE06471DED0097A5F4</string> + <string>1CA1AED706398EBD00589147</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.breakpointsV3</string> + <key>WindowString</key> + <string>315 424 744 409 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1CDDB66807F98D9800BB5817</string> + <key>WindowToolIsVisible</key> + <integer>1</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.debugAnimator</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>PBXNavigatorGroup</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Debug Visualizer</string> + <key>ServiceClasses</key> + <array> + <string>PBXNavigatorGroup</string> + </array> + <key>StatusbarIsVisible</key> + <integer>1</integer> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.debugAnimatorV3</string> + <key>WindowString</key> + <string>100 100 700 500 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.bookmarks</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>PBXBookmarksModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Bookmarks</string> + <key>ServiceClasses</key> + <array> + <string>PBXBookmarksModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>WindowString</key> + <string>538 42 401 187 0 0 1280 1002 </string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.projectFormatConflicts</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>Module</key> + <string>XCProjectFormatConflictsModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Project Format Conflicts</string> + <key>ServiceClasses</key> + <array> + <string>XCProjectFormatConflictsModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>WindowContentMinSize</key> + <string>450 300</string> + <key>WindowString</key> + <string>50 850 472 307 0 0 1440 877</string> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.classBrowser</string> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>ContentConfiguration</key> + <dict> + <key>OptionsSetName</key> + <string>Hierarchy, all classes</string> + <key>PBXProjectModuleGUID</key> + <string>1CA6456E063B45B4001379D8</string> + <key>PBXProjectModuleLabel</key> + <string>Class Browser - NSObject</string> + </dict> + <key>GeometryConfiguration</key> + <dict> + <key>ClassesFrame</key> + <string>{{0, 0}, {374, 96}}</string> + <key>ClassesTreeTableConfiguration</key> + <array> + <string>PBXClassNameColumnIdentifier</string> + <real>208</real> + <string>PBXClassBookColumnIdentifier</string> + <real>22</real> + </array> + <key>Frame</key> + <string>{{0, 0}, {630, 331}}</string> + <key>MembersFrame</key> + <string>{{0, 105}, {374, 395}}</string> + <key>MembersTreeTableConfiguration</key> + <array> + <string>PBXMemberTypeIconColumnIdentifier</string> + <real>22</real> + <string>PBXMemberNameColumnIdentifier</string> + <real>216</real> + <string>PBXMemberTypeColumnIdentifier</string> + <real>97</real> + <string>PBXMemberBookColumnIdentifier</string> + <real>22</real> + </array> + <key>PBXModuleWindowStatusBarHidden2</key> + <integer>1</integer> + <key>RubberWindowFrame</key> + <string>385 179 630 352 0 0 1440 878 </string> + </dict> + <key>Module</key> + <string>PBXClassBrowserModule</string> + <key>Proportion</key> + <string>332pt</string> + </dict> + </array> + <key>Proportion</key> + <string>332pt</string> + </dict> + </array> + <key>Name</key> + <string>Class Browser</string> + <key>ServiceClasses</key> + <array> + <string>PBXClassBrowserModule</string> + </array> + <key>StatusbarIsVisible</key> + <integer>0</integer> + <key>TableOfContents</key> + <array> + <string>1C0AD2AF069F1E9B00FABCE6</string> + <string>1C0AD2B0069F1E9B00FABCE6</string> + <string>1CA6456E063B45B4001379D8</string> + </array> + <key>ToolbarConfiguration</key> + <string>xcode.toolbar.config.classbrowser</string> + <key>WindowString</key> + <string>385 179 630 352 0 0 1440 878 </string> + <key>WindowToolGUID</key> + <string>1C0AD2AF069F1E9B00FABCE6</string> + <key>WindowToolIsVisible</key> + <integer>0</integer> + </dict> + <dict> + <key>Identifier</key> + <string>windowTool.refactoring</string> + <key>IncludeInToolsMenu</key> + <integer>0</integer> + <key>Layout</key> + <array> + <dict> + <key>Dock</key> + <array> + <dict> + <key>BecomeActive</key> + <integer>1</integer> + <key>GeometryConfiguration</key> + <dict> + <key>Frame</key> + <string>{0, 0}, {500, 335}</string> + <key>RubberWindowFrame</key> + <string>{0, 0}, {500, 335}</string> + </dict> + <key>Module</key> + <string>XCRefactoringModule</string> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Proportion</key> + <string>100%</string> + </dict> + </array> + <key>Name</key> + <string>Refactoring</string> + <key>ServiceClasses</key> + <array> + <string>XCRefactoringModule</string> + </array> + <key>WindowString</key> + <string>200 200 500 356 0 0 1920 1200 </string> + </dict> + </array> +</dict> +</plist> diff --git a/BalloonChallenge.xcodeproj/bwong.pbxuser b/BalloonChallenge.xcodeproj/bwong.pbxuser new file mode 100644 index 0000000..144d059 --- /dev/null +++ b/BalloonChallenge.xcodeproj/bwong.pbxuser @@ -0,0 +1,88 @@ +// !$*UTF8*$! +{ + 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { + activeExec = 0; + executables = ( + 1D6E99A8111D83E700661416 /* BalloonChallenge */, + ); + }; + 1D6E99A8111D83E700661416 /* BalloonChallenge */ = { + isa = PBXExecutable; + activeArgIndices = ( + ); + argumentStrings = ( + ); + autoAttachOnCrash = 1; + breakpointsEnabled = 0; + configStateDict = { + }; + customDataFormattersEnabled = 1; + dataTipCustomDataFormattersEnabled = 1; + dataTipShowTypeColumn = 1; + dataTipSortType = 0; + debuggerPlugin = GDBDebugging; + disassemblyDisplayState = 0; + enableDebugStr = 1; + environmentEntries = ( + ); + executableSystemSymbolLevel = 0; + executableUserSymbolLevel = 0; + libgmallocEnabled = 0; + name = BalloonChallenge; + showTypeColumn = 0; + sourceDirectories = ( + ); + }; + 1D6E99B1111D83EB00661416 /* Source Control */ = { + isa = PBXSourceControlManager; + fallbackIsa = XCSourceControlManager; + isSCMEnabled = 0; + scmConfiguration = { + repositoryNamesForRoots = { + "" = ""; + }; + }; + }; + 1D6E99B2111D83EB00661416 /* Code sense */ = { + isa = PBXCodeSenseManager; + indexTemplatePath = ""; + }; + 29B97313FDCFA39411CA2CEA /* Project object */ = { + activeBuildConfigurationName = Debug; + activeExecutable = 1D6E99A8111D83E700661416 /* BalloonChallenge */; + activeTarget = 1D6058900D05DD3D006BFB54 /* BalloonChallenge */; + codeSenseManager = 1D6E99B2111D83EB00661416 /* Code sense */; + executables = ( + 1D6E99A8111D83E700661416 /* BalloonChallenge */, + ); + perUserDictionary = { + PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { + PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; + PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; + PBXFileTableDataSourceColumnWidthsKey = ( + 20, + 341, + 20, + 48.16259765625, + 43, + 43, + 20, + ); + PBXFileTableDataSourceColumnsKey = ( + PBXFileDataSource_FiletypeID, + PBXFileDataSource_Filename_ColumnID, + PBXFileDataSource_Built_ColumnID, + PBXFileDataSource_ObjectSize_ColumnID, + PBXFileDataSource_Errors_ColumnID, + PBXFileDataSource_Warnings_ColumnID, + PBXFileDataSource_Target_ColumnID, + ); + }; + PBXPerProjectTemplateStateSaveDate = 287146983; + PBXWorkspaceStateSaveDate = 287146983; + }; + sourceControlManager = 1D6E99B1111D83EB00661416 /* Source Control */; + userBuildSettings = { + }; + }; +} diff --git a/BalloonChallenge.xcodeproj/project.pbxproj b/BalloonChallenge.xcodeproj/project.pbxproj new file mode 100755 index 0000000..6c7a4a5 --- /dev/null +++ b/BalloonChallenge.xcodeproj/project.pbxproj @@ -0,0 +1,249 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 45; + objects = { + +/* Begin PBXBuildFile section */ + 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */; }; + 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; + 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; + 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; + 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; }; + 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */; }; + 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 28AD733E0D9D9553002E5188 /* MainWindow.xib */; }; + 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeAppDelegate.h; sourceTree = "<group>"; }; + 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeAppDelegate.m; sourceTree = "<group>"; }; + 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BalloonChallenge.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + 288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = BalloonChallengeViewController.xib; sourceTree = "<group>"; }; + 28AD733E0D9D9553002E5188 /* MainWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MainWindow.xib; sourceTree = "<group>"; }; + 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallengeViewController.h; sourceTree = "<group>"; }; + 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BalloonChallengeViewController.m; sourceTree = "<group>"; }; + 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; + 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BalloonChallenge_Prefix.pch; sourceTree = "<group>"; }; + 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "BalloonChallenge-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, + 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, + 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 080E96DDFE201D6D7F000001 /* Classes */ = { + isa = PBXGroup; + children = ( + 1D3623240D0F684500981E51 /* BalloonChallengeAppDelegate.h */, + 1D3623250D0F684500981E51 /* BalloonChallengeAppDelegate.m */, + 28D7ACF60DDB3853001CB0EB /* BalloonChallengeViewController.h */, + 28D7ACF70DDB3853001CB0EB /* BalloonChallengeViewController.m */, + ); + path = Classes; + sourceTree = "<group>"; + }; + 19C28FACFE9D520D11CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */, + ); + name = Products; + sourceTree = "<group>"; + }; + 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { + isa = PBXGroup; + children = ( + 080E96DDFE201D6D7F000001 /* Classes */, + 29B97315FDCFA39411CA2CEA /* Other Sources */, + 29B97317FDCFA39411CA2CEA /* Resources */, + 29B97323FDCFA39411CA2CEA /* Frameworks */, + 19C28FACFE9D520D11CA2CBB /* Products */, + ); + name = CustomTemplate; + sourceTree = "<group>"; + }; + 29B97315FDCFA39411CA2CEA /* Other Sources */ = { + isa = PBXGroup; + children = ( + 32CA4F630368D1EE00C91783 /* BalloonChallenge_Prefix.pch */, + 29B97316FDCFA39411CA2CEA /* main.m */, + ); + name = "Other Sources"; + sourceTree = "<group>"; + }; + 29B97317FDCFA39411CA2CEA /* Resources */ = { + isa = PBXGroup; + children = ( + 2899E5210DE3E06400AC0155 /* BalloonChallengeViewController.xib */, + 28AD733E0D9D9553002E5188 /* MainWindow.xib */, + 8D1107310486CEB800E47090 /* BalloonChallenge-Info.plist */, + ); + name = Resources; + sourceTree = "<group>"; + }; + 29B97323FDCFA39411CA2CEA /* Frameworks */ = { + isa = PBXGroup; + children = ( + 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, + 1D30AB110D05D00D00671497 /* Foundation.framework */, + 288765A40DF7441C002DB57D /* CoreGraphics.framework */, + ); + name = Frameworks; + sourceTree = "<group>"; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 1D6058900D05DD3D006BFB54 /* BalloonChallenge */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */; + buildPhases = ( + 1D60588D0D05DD3D006BFB54 /* Resources */, + 1D60588E0D05DD3D006BFB54 /* Sources */, + 1D60588F0D05DD3D006BFB54 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = BalloonChallenge; + productName = BalloonChallenge; + productReference = 1D6058910D05DD3D006BFB54 /* BalloonChallenge.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 29B97313FDCFA39411CA2CEA /* Project object */ = { + isa = PBXProject; + buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */; + compatibilityVersion = "Xcode 3.1"; + hasScannedForEncodings = 1; + mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 1D6058900D05DD3D006BFB54 /* BalloonChallenge */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 1D60588D0D05DD3D006BFB54 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 28AD733F0D9D9553002E5188 /* MainWindow.xib in Resources */, + 2899E5220DE3E06400AC0155 /* BalloonChallengeViewController.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 1D60588E0D05DD3D006BFB54 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1D60589B0D05DD56006BFB54 /* main.m in Sources */, + 1D3623260D0F684500981E51 /* BalloonChallengeAppDelegate.m in Sources */, + 28D7ACF80DDB3853001CB0EB /* BalloonChallengeViewController.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 1D6058940D05DD3E006BFB54 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; + INFOPLIST_FILE = "BalloonChallenge-Info.plist"; + PRODUCT_NAME = BalloonChallenge; + }; + name = Debug; + }; + 1D6058950D05DD3E006BFB54 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = YES; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = BalloonChallenge_Prefix.pch; + INFOPLIST_FILE = "BalloonChallenge-Info.plist"; + PRODUCT_NAME = BalloonChallenge; + }; + name = Release; + }; + C01FCF4F08A954540054247B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + PREBINDING = NO; + SDKROOT = iphoneos3.1.2; + }; + name = Debug; + }; + C01FCF5008A954540054247B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + PREBINDING = NO; + SDKROOT = iphoneos3.1.2; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "BalloonChallenge" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D6058940D05DD3E006BFB54 /* Debug */, + 1D6058950D05DD3E006BFB54 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C01FCF4E08A954540054247B /* Build configuration list for PBXProject "BalloonChallenge" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C01FCF4F08A954540054247B /* Debug */, + C01FCF5008A954540054247B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; +} diff --git a/BalloonChallengeViewController.xib b/BalloonChallengeViewController.xib new file mode 100644 index 0000000..c8ed129 --- /dev/null +++ b/BalloonChallengeViewController.xib @@ -0,0 +1,151 @@ +<?xml version="1.0" encoding="UTF-8"?> +<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> + <data> + <int key="IBDocument.SystemTarget">784</int> + <string key="IBDocument.SystemVersion">10A394</string> + <string key="IBDocument.InterfaceBuilderVersion">732</string> + <string key="IBDocument.AppKitVersion">1027.1</string> + <string key="IBDocument.HIToolboxVersion">430.00</string> + <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> + <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string key="NS.object.0">60</string> + </object> + <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> + <bool key="EncodedWithXMLCoder">YES</bool> + <integer value="6"/> + </object> + <object class="NSArray" key="IBDocument.PluginDependencies"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + <object class="NSMutableDictionary" key="IBDocument.Metadata"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys" id="0"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBProxyObject" id="372490531"> + <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> + </object> + <object class="IBProxyObject" id="843779117"> + <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> + </object> + <object class="IBUIView" id="774585933"> + <reference key="NSNextResponder"/> + <int key="NSvFlags">274</int> + <string key="NSFrameSize">{320, 460}</string> + <reference key="NSSuperview"/> + <object class="NSColor" key="IBUIBackgroundColor"> + <int key="NSColorSpace">3</int> + <bytes key="NSWhite">MC43NQA</bytes> + <object class="NSColorSpace" key="NSCustomColorSpace"> + <int key="NSID">2</int> + </object> + </object> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + </object> + <object class="IBObjectContainer" key="IBDocument.Objects"> + <object class="NSMutableArray" key="connectionRecords"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">view</string> + <reference key="source" ref="372490531"/> + <reference key="destination" ref="774585933"/> + </object> + <int key="connectionID">7</int> + </object> + </object> + <object class="IBMutableOrderedSet" key="objectRecords"> + <object class="NSArray" key="orderedObjects"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBObjectRecord"> + <int key="objectID">0</int> + <reference key="object" ref="0"/> + <reference key="children" ref="1000"/> + <nil key="parent"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-1</int> + <reference key="object" ref="372490531"/> + <reference key="parent" ref="0"/> + <string key="objectName">File's Owner</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-2</int> + <reference key="object" ref="843779117"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">6</int> + <reference key="object" ref="774585933"/> + <reference key="parent" ref="0"/> + </object> + </object> + </object> + <object class="NSMutableDictionary" key="flattenedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>-1.CustomClassName</string> + <string>-2.CustomClassName</string> + <string>6.IBEditorWindowLastContentRect</string> + <string>6.IBPluginDependency</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>BalloonChallengeViewController</string> + <string>UIResponder</string> + <string>{{438, 347}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + </object> + <object class="NSMutableDictionary" key="unlocalizedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="activeLocalization"/> + <object class="NSMutableDictionary" key="localizations"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="sourceID"/> + <int key="maxID">7</int> + </object> + <object class="IBClassDescriber" key="IBDocument.Classes"> + <object class="NSMutableArray" key="referencedPartialClassDescriptions"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">BalloonChallengeViewController</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">Classes/BalloonChallengeViewController.h</string> + </object> + </object> + </object> + </object> + <int key="IBDocument.localizationMode">0</int> + <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> + <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> + <integer value="3100" key="NS.object.0"/> + </object> + <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> + <string key="IBDocument.LastKnownRelativeProjectPath">BalloonChallenge.xcodeproj</string> + <int key="IBDocument.defaultPropertyAccessControl">3</int> + <string key="IBCocoaTouchPluginVersion">3.1</string> + </data> +</archive> diff --git a/BalloonChallenge_Prefix.pch b/BalloonChallenge_Prefix.pch new file mode 100644 index 0000000..fc5ebc1 --- /dev/null +++ b/BalloonChallenge_Prefix.pch @@ -0,0 +1,8 @@ +// +// Prefix header for all source files of the 'BalloonChallenge' target in the 'BalloonChallenge' project +// + +#ifdef __OBJC__ + #import <Foundation/Foundation.h> + #import <UIKit/UIKit.h> +#endif diff --git a/Classes/BalloonChallengeAppDelegate.h b/Classes/BalloonChallengeAppDelegate.h new file mode 100644 index 0000000..6ba3b7b --- /dev/null +++ b/Classes/BalloonChallengeAppDelegate.h @@ -0,0 +1,22 @@ +// +// BalloonChallengeAppDelegate.h +// BalloonChallenge +// +// Created by Brian Wong on 2/6/10. +// Copyright __MyCompanyName__ 2010. All rights reserved. +// + +#import <UIKit/UIKit.h> + +@class BalloonChallengeViewController; + +@interface BalloonChallengeAppDelegate : NSObject <UIApplicationDelegate> { + UIWindow *window; + BalloonChallengeViewController *viewController; +} + +@property (nonatomic, retain) IBOutlet UIWindow *window; +@property (nonatomic, retain) IBOutlet BalloonChallengeViewController *viewController; + +@end + diff --git a/Classes/BalloonChallengeAppDelegate.m b/Classes/BalloonChallengeAppDelegate.m new file mode 100644 index 0000000..7919edf --- /dev/null +++ b/Classes/BalloonChallengeAppDelegate.m @@ -0,0 +1,33 @@ +// +// BalloonChallengeAppDelegate.m +// BalloonChallenge +// +// Created by Brian Wong on 2/6/10. +// Copyright __MyCompanyName__ 2010. All rights reserved. +// + +#import "BalloonChallengeAppDelegate.h" +#import "BalloonChallengeViewController.h" + +@implementation BalloonChallengeAppDelegate + +@synthesize window; +@synthesize viewController; + + +- (void)applicationDidFinishLaunching:(UIApplication *)application { + + // Override point for customization after app launch + [window addSubview:viewController.view]; + [window makeKeyAndVisible]; +} + + +- (void)dealloc { + [viewController release]; + [window release]; + [super dealloc]; +} + + +@end diff --git a/Classes/BalloonChallengeViewController.h b/Classes/BalloonChallengeViewController.h new file mode 100644 index 0000000..c50f03e --- /dev/null +++ b/Classes/BalloonChallengeViewController.h @@ -0,0 +1,16 @@ +// +// BalloonChallengeViewController.h +// BalloonChallenge +// +// Created by Brian Wong on 2/6/10. +// Copyright __MyCompanyName__ 2010. All rights reserved. +// + +#import <UIKit/UIKit.h> + +@interface BalloonChallengeViewController : UIViewController { + +} + +@end + diff --git a/Classes/BalloonChallengeViewController.m b/Classes/BalloonChallengeViewController.m new file mode 100644 index 0000000..01cdfdf --- /dev/null +++ b/Classes/BalloonChallengeViewController.m @@ -0,0 +1,65 @@ +// +// BalloonChallengeViewController.m +// BalloonChallenge +// +// Created by Brian Wong on 2/6/10. +// Copyright __MyCompanyName__ 2010. All rights reserved. +// + +#import "BalloonChallengeViewController.h" + +@implementation BalloonChallengeViewController + + + +/* +// The designated initializer. Override to perform setup that is required before the view is loaded. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { + // Custom initialization + } + return self; +} +*/ + +/* +// Implement loadView to create a view hierarchy programmatically, without using a nib. +- (void)loadView { +} +*/ + + +/* +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} +*/ + + +/* +// Override to allow orientations other than the default portrait orientation. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + // Return YES for supported orientations + return (interfaceOrientation == UIInterfaceOrientationPortrait); +} +*/ + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + +@end diff --git a/MainWindow.xib b/MainWindow.xib new file mode 100644 index 0000000..5484589 --- /dev/null +++ b/MainWindow.xib @@ -0,0 +1,219 @@ +<?xml version="1.0" encoding="UTF-8"?> +<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10"> + <data> + <int key="IBDocument.SystemTarget">784</int> + <string key="IBDocument.SystemVersion">10A394</string> + <string key="IBDocument.InterfaceBuilderVersion">732</string> + <string key="IBDocument.AppKitVersion">1027.1</string> + <string key="IBDocument.HIToolboxVersion">430.00</string> + <object class="NSMutableDictionary" key="IBDocument.PluginVersions"> + <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string key="NS.object.0">60</string> + </object> + <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> + <bool key="EncodedWithXMLCoder">YES</bool> + <integer value="10"/> + </object> + <object class="NSArray" key="IBDocument.PluginDependencies"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + <object class="NSMutableDictionary" key="IBDocument.Metadata"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys" id="0"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBProxyObject" id="841351856"> + <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> + </object> + <object class="IBProxyObject" id="427554174"> + <string key="IBProxiedObjectIdentifier">IBFirstResponder</string> + </object> + <object class="IBUICustomObject" id="664661524"/> + <object class="IBUIViewController" id="943309135"> + <string key="IBUINibName">BalloonChallengeViewController</string> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + <object class="IBUIWindow" id="117978783"> + <nil key="NSNextResponder"/> + <int key="NSvFlags">292</int> + <string key="NSFrameSize">{320, 480}</string> + <object class="NSColor" key="IBUIBackgroundColor"> + <int key="NSColorSpace">1</int> + <bytes key="NSRGB">MSAxIDEAA</bytes> + </object> + <bool key="IBUIOpaque">NO</bool> + <bool key="IBUIClearsContextBeforeDrawing">NO</bool> + <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/> + </object> + </object> + <object class="IBObjectContainer" key="IBDocument.Objects"> + <object class="NSMutableArray" key="connectionRecords"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">delegate</string> + <reference key="source" ref="841351856"/> + <reference key="destination" ref="664661524"/> + </object> + <int key="connectionID">4</int> + </object> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">viewController</string> + <reference key="source" ref="664661524"/> + <reference key="destination" ref="943309135"/> + </object> + <int key="connectionID">11</int> + </object> + <object class="IBConnectionRecord"> + <object class="IBCocoaTouchOutletConnection" key="connection"> + <string key="label">window</string> + <reference key="source" ref="664661524"/> + <reference key="destination" ref="117978783"/> + </object> + <int key="connectionID">14</int> + </object> + </object> + <object class="IBMutableOrderedSet" key="objectRecords"> + <object class="NSArray" key="orderedObjects"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBObjectRecord"> + <int key="objectID">0</int> + <reference key="object" ref="0"/> + <reference key="children" ref="1000"/> + <nil key="parent"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-1</int> + <reference key="object" ref="841351856"/> + <reference key="parent" ref="0"/> + <string key="objectName">File's Owner</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">3</int> + <reference key="object" ref="664661524"/> + <reference key="parent" ref="0"/> + <string key="objectName">BalloonChallenge App Delegate</string> + </object> + <object class="IBObjectRecord"> + <int key="objectID">-2</int> + <reference key="object" ref="427554174"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">10</int> + <reference key="object" ref="943309135"/> + <reference key="parent" ref="0"/> + </object> + <object class="IBObjectRecord"> + <int key="objectID">12</int> + <reference key="object" ref="117978783"/> + <reference key="parent" ref="0"/> + </object> + </object> + </object> + <object class="NSMutableDictionary" key="flattenedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>-1.CustomClassName</string> + <string>-2.CustomClassName</string> + <string>10.CustomClassName</string> + <string>10.IBEditorWindowLastContentRect</string> + <string>10.IBPluginDependency</string> + <string>12.IBEditorWindowLastContentRect</string> + <string>12.IBPluginDependency</string> + <string>3.CustomClassName</string> + <string>3.IBPluginDependency</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>UIApplication</string> + <string>UIResponder</string> + <string>BalloonChallengeViewController</string> + <string>{{512, 351}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>{{525, 346}, {320, 480}}</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + <string>BalloonChallengeAppDelegate</string> + <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string> + </object> + </object> + <object class="NSMutableDictionary" key="unlocalizedProperties"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="activeLocalization"/> + <object class="NSMutableDictionary" key="localizations"> + <bool key="EncodedWithXMLCoder">YES</bool> + <reference key="dict.sortedKeys" ref="0"/> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + </object> + </object> + <nil key="sourceID"/> + <int key="maxID">14</int> + </object> + <object class="IBClassDescriber" key="IBDocument.Classes"> + <object class="NSMutableArray" key="referencedPartialClassDescriptions"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="IBPartialClassDescription"> + <string key="className">BalloonChallengeAppDelegate</string> + <string key="superclassName">NSObject</string> + <object class="NSMutableDictionary" key="outlets"> + <bool key="EncodedWithXMLCoder">YES</bool> + <object class="NSArray" key="dict.sortedKeys"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>viewController</string> + <string>window</string> + </object> + <object class="NSMutableArray" key="dict.values"> + <bool key="EncodedWithXMLCoder">YES</bool> + <string>BalloonChallengeViewController</string> + <string>UIWindow</string> + </object> + </object> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">Classes/BalloonChallengeAppDelegate.h</string> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">BalloonChallengeAppDelegate</string> + <string key="superclassName">NSObject</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBUserSource</string> + <string key="minorKey"/> + </object> + </object> + <object class="IBPartialClassDescription"> + <string key="className">BalloonChallengeViewController</string> + <string key="superclassName">UIViewController</string> + <object class="IBClassDescriptionSource" key="sourceIdentifier"> + <string key="majorKey">IBProjectSource</string> + <string key="minorKey">Classes/BalloonChallengeViewController.h</string> + </object> + </object> + </object> + </object> + <int key="IBDocument.localizationMode">0</int> + <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies"> + <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string> + <integer value="3100" key="NS.object.0"/> + </object> + <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool> + <string key="IBDocument.LastKnownRelativeProjectPath">BalloonChallenge.xcodeproj</string> + <int key="IBDocument.defaultPropertyAccessControl">3</int> + <string key="IBCocoaTouchPluginVersion">3.1</string> + </data> +</archive> diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/categories.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/categories.pbxbtree new file mode 100644 index 0000000..42392f2 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/categories.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree new file mode 100644 index 0000000..865cfd4 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/cdecls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree new file mode 100644 index 0000000..538e82a Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/decls.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree new file mode 100644 index 0000000..36dfbae Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/files.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree new file mode 100644 index 0000000..b49009e Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/imports.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header new file mode 100644 index 0000000..1a0a2a6 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/pbxindex.header differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree new file mode 100644 index 0000000..946d327 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/protocols.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree new file mode 100644 index 0000000..a9fa23f Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/refs.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control new file mode 100644 index 0000000..99b3547 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/control differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings new file mode 100644 index 0000000..370a045 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/strings.pbxstrings/strings differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree new file mode 100644 index 0000000..62d1c29 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/subclasses.pbxbtree differ diff --git a/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols new file mode 100644 index 0000000..abc6789 Binary files /dev/null and b/build/BalloonChallenge.build/BalloonChallenge.pbxindex/symbols0.pbxsymbols differ diff --git a/main.m b/main.m new file mode 100644 index 0000000..2d0a29c --- /dev/null +++ b/main.m @@ -0,0 +1,17 @@ +// +// main.m +// BalloonChallenge +// +// Created by Brian Wong on 2/6/10. +// Copyright __MyCompanyName__ 2010. All rights reserved. +// + +#import <UIKit/UIKit.h> + +int main(int argc, char *argv[]) { + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, argv, nil, nil); + [pool release]; + return retVal; +}
alexbowe/cardgen
c519374c86678c83c9deb5253a09046fd4d30f14
hacked up formatting, not nested
diff --git a/cardgen.py b/cardgen.py index 2514d79..3b63274 100755 --- a/cardgen.py +++ b/cardgen.py @@ -1,69 +1,89 @@ #!/usr/bin/env python from cheetah.Template import Template import re, sys, optparse template = 'template.tex' # Doesn't support multi-line titles... Might convert to ANTLR later # to support easier modification. # http://www.antlr.org re_text = r'^(.+):$\n((?:\n?.+)+)\n*' rec = re.compile(re_text, re.MULTILINE) +# initial pass maps delimiters to formatting +formats = { r'\*' : r'\textbf{%s}', + r'\+': r'\emph{%s}', + '_': r'\underline{%s}' } + +def text_mapper(formats): + regex = r'' + for (i, (delimiter, _)) in enumerate(formats.items()): + if i > 0: regex += '|' + regex += r'%s(.*)%s' % (delimiter, delimiter) + r = re.compile(regex) + def map_match(match): + for (i, item) in enumerate(match.groups()): + if item is not None: + fmt = formats.items()[i][1] + return fmt % item + sub = lambda string: r.sub(map_match, string) + return sub + # Eat stderr class Discarder(object): def write(self, text): pass def fillTemplate(cards): # get rid of cheetah stderr output temp = sys.stderr sys.stderr = Discarder() output = str(Template(file=template, searchList = { 'cards': cards })) # restore stderr sys.stderr = temp return output def compileFromString(instring): iterator = rec.finditer(instring) return fillTemplate(iterator) def compile(infile, outfile): instring = infile.read() - output = compileFromString(instring) + transform = text_mapper(formats) + output = compileFromString(transform(instring)) outfile.write(output) def fileHandledExec(func, infile=None, outfile=None): if func is None: return if infile is None: infile = sys.stdin else: infile = open(infile, 'r') if outfile is None: outfile = sys.stdout else: outfile = open(outfile, 'w') func(infile, outfile) if infile is not sys.stdin: infile.close() if outfile is not sys.stdout: outfile.close() def main(): p = optparse.OptionParser() p.add_option('-i', '--input', help='Card definition file') p.add_option('-o', '--output', help='Output File') options, args = p.parse_args() fileHandledExec(compile, options.input, options.output) if __name__ == '__main__': - main() \ No newline at end of file + main()
alexbowe/cardgen
0d79680f6ed5364cbadc3ba08dab2abea286c94d
clone instructions
diff --git a/readme.markdown b/readme.markdown index 97d8364..03b37e5 100644 --- a/readme.markdown +++ b/readme.markdown @@ -1,31 +1,37 @@ Cardgen ======= To build an example, run makefile to generate design pattern cards from intents.txt +To clone this repository, type from your command line (with git installed): + + git clone http://github.com/alexbowe/cardgen.git + +This will make a folder 'cardgen' in the working directory and populate it. + Cardgen Usage ------------- For help: ./cardgen.py -h To run: ./cardgen.py -i inputfile -o outputfile or using stdin/stdout: ./cardgen.py < inputfile > outputfile Inputfile Structure ------------------- First Card: Definition Line 1 Definition Line 2 Second Card: Single Line Definition \ No newline at end of file
alexbowe/cardgen
e46f5227b86f88ecaaab0c400f551cc65d3e2b6b
refactoring
diff --git a/cardgen.py b/cardgen.py index 3387f40..2514d79 100755 --- a/cardgen.py +++ b/cardgen.py @@ -1,49 +1,69 @@ #!/usr/bin/env python from cheetah.Template import Template import re, sys, optparse template = 'template.tex' +# Doesn't support multi-line titles... Might convert to ANTLR later +# to support easier modification. +# http://www.antlr.org re_text = r'^(.+):$\n((?:\n?.+)+)\n*' rec = re.compile(re_text, re.MULTILINE) # Eat stderr class Discarder(object): def write(self, text): pass -def getMatches(file): - text = file.read() - matches = rec.finditer(text) - return matches - -def main(): - p = optparse.OptionParser() - p.add_option('-i', '--input', help='Card definition file') - p.add_option('-o', '--output', help='Output File') - options, args = p.parse_args() - - infile = sys.stdin - outfile = sys.stdout - - if options.input is not None: - infile = open(str(options.input), 'r') - - if options.output is not None: - outfile = open(str(options.output), 'w') - - cards = getMatches(infile) - +def fillTemplate(cards): # get rid of cheetah stderr output temp = sys.stderr sys.stderr = Discarder() - outfile.write(str(Template(file=template, searchList = { 'cards': cards }))) + + output = str(Template(file=template, searchList = { 'cards': cards })) + # restore stderr sys.stderr = temp - if options.input is not None: + return output + +def compileFromString(instring): + iterator = rec.finditer(instring) + return fillTemplate(iterator) + +def compile(infile, outfile): + instring = infile.read() + output = compileFromString(instring) + outfile.write(output) + +def fileHandledExec(func, infile=None, outfile=None): + if func is None: + return + + if infile is None: + infile = sys.stdin + else: + infile = open(infile, 'r') + + if outfile is None: + outfile = sys.stdout + else: + outfile = open(outfile, 'w') + + func(infile, outfile) + + if infile is not sys.stdin: infile.close() - if options.output is not None: + + if outfile is not sys.stdout: outfile.close() +def main(): + p = optparse.OptionParser() + p.add_option('-i', '--input', help='Card definition file') + p.add_option('-o', '--output', help='Output File') + options, args = p.parse_args() + + fileHandledExec(compile, options.input, options.output) + if __name__ == '__main__': main() \ No newline at end of file
alexbowe/cardgen
15389a75fdc3bdf733d53575eec0a61b4d0e8908
modified cardgen to use provided cheetah lib
diff --git a/cardgen.py b/cardgen.py index 1d10458..3387f40 100755 --- a/cardgen.py +++ b/cardgen.py @@ -1,49 +1,49 @@ #!/usr/bin/env python -from Cheetah.Template import Template +from cheetah.Template import Template import re, sys, optparse template = 'template.tex' re_text = r'^(.+):$\n((?:\n?.+)+)\n*' rec = re.compile(re_text, re.MULTILINE) # Eat stderr class Discarder(object): def write(self, text): pass def getMatches(file): text = file.read() matches = rec.finditer(text) return matches def main(): p = optparse.OptionParser() p.add_option('-i', '--input', help='Card definition file') p.add_option('-o', '--output', help='Output File') options, args = p.parse_args() infile = sys.stdin outfile = sys.stdout if options.input is not None: infile = open(str(options.input), 'r') if options.output is not None: outfile = open(str(options.output), 'w') cards = getMatches(infile) # get rid of cheetah stderr output temp = sys.stderr sys.stderr = Discarder() outfile.write(str(Template(file=template, searchList = { 'cards': cards }))) # restore stderr sys.stderr = temp if options.input is not None: infile.close() if options.output is not None: outfile.close() if __name__ == '__main__': main() \ No newline at end of file
alexbowe/cardgen
f40523e3f00063389d94876e62ec1e79d2ace915
gitignore file
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3669fd7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# LaTeX # +*.aux +*.log + +# Python # +*.pyc + +# OS Stuff # +.DS_Store \ No newline at end of file diff --git a/cardgen.py b/cardgen.py index e574571..1d10458 100755 --- a/cardgen.py +++ b/cardgen.py @@ -1,49 +1,49 @@ #!/usr/bin/env python from Cheetah.Template import Template import re, sys, optparse template = 'template.tex' -re_text = '^(.+):$\n((?:\n?.+)+)\n*' +re_text = r'^(.+):$\n((?:\n?.+)+)\n*' rec = re.compile(re_text, re.MULTILINE) # Eat stderr class Discarder(object): def write(self, text): pass def getMatches(file): text = file.read() matches = rec.finditer(text) return matches def main(): p = optparse.OptionParser() p.add_option('-i', '--input', help='Card definition file') p.add_option('-o', '--output', help='Output File') options, args = p.parse_args() infile = sys.stdin outfile = sys.stdout if options.input is not None: infile = open(str(options.input), 'r') if options.output is not None: outfile = open(str(options.output), 'w') cards = getMatches(infile) # get rid of cheetah stderr output temp = sys.stderr sys.stderr = Discarder() outfile.write(str(Template(file=template, searchList = { 'cards': cards }))) # restore stderr sys.stderr = temp if options.input is not None: infile.close() if options.output is not None: outfile.close() if __name__ == '__main__': main() \ No newline at end of file
alexbowe/cardgen
1f2a39a824d3cf6580f1af52ad36bf59ecf8b554
fixed some mistakes
diff --git a/readme.markdown b/readme.markdown index eb39959..97d8364 100644 --- a/readme.markdown +++ b/readme.markdown @@ -1,31 +1,31 @@ Cardgen ======= -To build example design pattern intent cards, run makefile to generate design pattern cards from intents.txt +To build an example, run makefile to generate design pattern cards from intents.txt Cardgen Usage ------------- For help: ./cardgen.py -h To run: ./cardgen.py -i inputfile -o outputfile or using stdin/stdout: ./cardgen.py < inputfile > outputfile Inputfile Structure ------------------- First Card: Definition Line 1 Definition Line 2 Second Card: Single Line Definition \ No newline at end of file
alexbowe/cardgen
3bd702bae6de1c36e7ff13564673077726a9fedc
fixed some mistakes
diff --git a/readme.markdown b/readme.markdown index a9bc628..eb39959 100644 --- a/readme.markdown +++ b/readme.markdown @@ -1,31 +1,31 @@ Cardgen ======= -To build example design pattern intent cards, run make on makefile to generate design pattern cards from intents.txt +To build example design pattern intent cards, run makefile to generate design pattern cards from intents.txt Cardgen Usage ------------- For help: ./cardgen.py -h To run: ./cardgen.py -i inputfile -o outputfile or using stdin/stdout: ./cardgen.py < inputfile > outputfile Inputfile Structure ------------------- First Card: Definition Line 1 Definition Line 2 Second Card: Single Line Definition \ No newline at end of file
alexbowe/cardgen
2976c4ea7d4bec83f8b248f6e91b9db07e315397
fixed some mistakes
diff --git a/intents.pdf b/intents.pdf new file mode 100644 index 0000000..4e0c3c0 Binary files /dev/null and b/intents.pdf differ diff --git a/readme.markdown b/readme.markdown index 60e1b62..a9bc628 100644 --- a/readme.markdown +++ b/readme.markdown @@ -1,22 +1,31 @@ Cardgen ======= -Run make on makefile to generate design pattern cards from intents.txt +To build example design pattern intent cards, run make on makefile to generate design pattern cards from intents.txt + Cardgen Usage ------------- - ./cardgen.py -h for help +For help: + + ./cardgen.py -h - ./cardgen.py -i <inputfile> -o <outputfile> +To run: -OR (using pipes): + ./cardgen.py -i inputfile -o outputfile - cat <inputfile> | ./flashgen.py > <outputfile> +or using stdin/stdout: + ./cardgen.py < inputfile > outputfile + Inputfile Structure ------------------- - Title: - Definition (can take multiple lines) \ No newline at end of file + First Card: + Definition Line 1 + Definition Line 2 + + Second Card: + Single Line Definition \ No newline at end of file
alexbowe/cardgen
67e43476df92ecbb485b31b2bccf856a68bf520c
fixed issue with readme code blocks
diff --git a/readme.markdown b/readme.markdown index a8914cd..60e1b62 100644 --- a/readme.markdown +++ b/readme.markdown @@ -1,19 +1,22 @@ +Cardgen +======= + Run make on makefile to generate design pattern cards from intents.txt Cardgen Usage -============= +------------- -./cardgen.py -h for help + ./cardgen.py -h for help -./cardgen.py -i <inputfile> -o <outputfile> + ./cardgen.py -i <inputfile> -o <outputfile> OR (using pipes): -cat <inputfile> | ./flashgen.py > <outputfile> + cat <inputfile> | ./flashgen.py > <outputfile> Inputfile Structure -=================== +------------------- -Title: -Definition \ No newline at end of file + Title: + Definition (can take multiple lines) \ No newline at end of file
alexbowe/cardgen
9e247c5a6df81bd6c1e15e5581c3ced100581a48
template used by cardgen
diff --git a/template.tex b/template.tex new file mode 100644 index 0000000..1dd899c --- /dev/null +++ b/template.tex @@ -0,0 +1,12 @@ +\documentclass[avery5371,frame]{flashcards} + +\begin{document} + +#for $card in $cards +\begin{flashcard}{$card.group(1)} +$card.group(2) +\end{flashcard} + + +#end for +\end{document}
alexbowe/cardgen
a9929dd49803029cb6709b292d803de16e435fae
design pattern intents
diff --git a/intents.txt b/intents.txt new file mode 100644 index 0000000..d2c8aaf --- /dev/null +++ b/intents.txt @@ -0,0 +1,68 @@ +Abstract Factory: +Provides an interface for creating families of related or dependent objects without specifying their concrete classes. + +Builder: +Separates the construction of a complex object from its representation so that the same construction process can create different representations. + +Factory Method: +Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses. + +Prototype: +Specifies the kinds of objects to create using an instance, and creates new objects by copying this instance. + +Singleton: +Ensures a class has only one instance, and provides a global point of access to it. + +Adapter: +Converts the interface of a class into another interface clients expect. Lets classes work together that couldn't otherwise because of incompatible interfaces. + +Bridge: +Decouples an abstraction from its implementation so that the two can vary independently. + +Composite: +Organises objects into tree structures to represent whole-part hierarchies. This pattern lets clients treat individual objects and object compositions uniformly. + +Decorator: +Attaches additional responsibilities to an object dynamically. Provides a flexible alternative to subclassing for extending functionality. + +Facade: +Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use. + +Flyweight: +Uses sharing to support large numbers of fine-grained objects efficiently. + +Proxy: +Provides a surrogate or placeholder for another object to control access to it. + +Chain of Responsibility: +Avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. + +Command: +Encapsulates a request as an object, thereby letting you parameterise clients with different requests, queue or log requests, and support undoable operations. + +Interpreter: +Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. + +Iterator: +Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. + +Mediator: +Defines an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. + +Memento: +Without violating encapsulation, capture and externalise an object's internal state so that the object can be restored to this state later. + +Observer: +Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. + +State: +Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class. + +Strategy: +Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Lets the algorithm vary independently from the clients that use it. + +Template Method: +Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. + +Visitor: +Represents an operation to be performed on the elements of an object structure. Lets you define a new operation without changing the classes of the elements on which it operates.
alexbowe/cardgen
4aabc274acb7ac3f97d2bc9b02fbc9b3a049320b
add naive makefile for building design pattern intent cards
diff --git a/makefile b/makefile new file mode 100644 index 0000000..52c8ccb --- /dev/null +++ b/makefile @@ -0,0 +1,8 @@ +intents.pdf: intents.tex + pdflatex intents.tex + +intents.tex: intents.txt + python cardgen.py -i intents.txt -o intents.tex + +clean: + rm -rf *.log *.aux intents.tex *.pdf \ No newline at end of file
alexbowe/cardgen
d518fc00340803b1bb11daad5fa1cd2b82b39e78
add python script for reading flashcard definitions and filling in the template
diff --git a/cardgen.py b/cardgen.py new file mode 100755 index 0000000..e574571 --- /dev/null +++ b/cardgen.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +from Cheetah.Template import Template +import re, sys, optparse + +template = 'template.tex' +re_text = '^(.+):$\n((?:\n?.+)+)\n*' +rec = re.compile(re_text, re.MULTILINE) + +# Eat stderr +class Discarder(object): + def write(self, text): + pass + +def getMatches(file): + text = file.read() + matches = rec.finditer(text) + return matches + +def main(): + p = optparse.OptionParser() + p.add_option('-i', '--input', help='Card definition file') + p.add_option('-o', '--output', help='Output File') + options, args = p.parse_args() + + infile = sys.stdin + outfile = sys.stdout + + if options.input is not None: + infile = open(str(options.input), 'r') + + if options.output is not None: + outfile = open(str(options.output), 'w') + + cards = getMatches(infile) + + # get rid of cheetah stderr output + temp = sys.stderr + sys.stderr = Discarder() + outfile.write(str(Template(file=template, searchList = { 'cards': cards }))) + # restore stderr + sys.stderr = temp + + if options.input is not None: + infile.close() + if options.output is not None: + outfile.close() + +if __name__ == '__main__': + main() \ No newline at end of file
alexbowe/cardgen
80df4c18c1b3cc82379103fb2836e60c97436e23
add flashcards class and config from CTAN
diff --git a/avery5371.cfg b/avery5371.cfg new file mode 100644 index 0000000..e36d36c --- /dev/null +++ b/avery5371.cfg @@ -0,0 +1,56 @@ +%% +%% This is file `avery5371.cfg', +%% generated with the docstrip utility. +%% +%% The original source files were: +%% +%% flashcards.dtx (with options: `avery5371') +%% +%% FlashCards LaTeX2e Class for Typesetting Double Sided Cards +%% Copyright (C) 2000 Alexander M. Budge <[email protected]> +%% +%% This program is free software; you can redistribute it and/or modify +%% it under the terms of the GNU General Public License as published by +%% the Free Software Foundation; either version 2 of the License, or +%% (at your option) any later version. +%% +%% This program is distributed in the hope that it will be useful, +%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +%% GNU General Public License for more details. +%% +%% You should have received a copy of the GNU General Public License +%% along with this program (the file COPYING); if not, write to the +%% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +%% +%% \CharacterTable +%% {Upper-case \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z +%% Lower-case \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z +%% Digits \0\1\2\3\4\5\6\7\8\9 +%% Exclamation \! Double quote \" Hash (number) \# +%% Dollar \$ Percent \% Ampersand \& +%% Acute accent \' Left paren \( Right paren \) +%% Asterisk \* Plus \+ Comma \, +%% Minus \- Point \. Solidus \/ +%% Colon \: Semicolon \; Less than \< +%% Equals \= Greater than \> Question mark \? +%% Commercial at \@ Left bracket \[ Backslash \\ +%% Right bracket \] Circumflex \^ Underscore \_ +%% Grave accent \` Left brace \{ Vertical bar \| +%% Right brace \} Tilde \~} +%% +\NeedsTeXFormat{LaTeX2e}[1996/12/01] +\ProvidesFile{avery5371.cfg} +\newcommand{\cardpapermode}{portrait} +\newcommand{\cardpaper}{letterpaper} +\newcommand{\cardrows}{5} +\newcommand{\cardcolumns}{2} +\setlength{\cardheight}{2.0in} +\setlength{\cardwidth}{3.5in} +\setlength{\topoffset}{0.50in} +\setlength{\oddoffset}{0.75in} +\setlength{\evenoffset}{0.75in} + +\endinput +%% +%% End of file `avery5371.cfg'. diff --git a/flashcards.cls b/flashcards.cls new file mode 100644 index 0000000..05c7dd5 --- /dev/null +++ b/flashcards.cls @@ -0,0 +1,334 @@ +%% +%% This is file `flashcards.cls', +%% generated with the docstrip utility. +%% +%% The original source files were: +%% +%% flashcards.dtx (with options: `flashcards') +%% +%% FlashCards LaTeX2e Class for Typesetting Double Sided Cards +%% Copyright (C) 2000 Alexander M. Budge <[email protected]> +%% +%% This program is free software; you can redistribute it and/or modify +%% it under the terms of the GNU General Public License as published by +%% the Free Software Foundation; either version 2 of the License, or +%% (at your option) any later version. +%% +%% This program is distributed in the hope that it will be useful, +%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +%% GNU General Public License for more details. +%% +%% You should have received a copy of the GNU General Public License +%% along with this program (the file COPYING); if not, write to the +%% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +%% +%% \CharacterTable +%% {Upper-case \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z +%% Lower-case \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z +%% Digits \0\1\2\3\4\5\6\7\8\9 +%% Exclamation \! Double quote \" Hash (number) \# +%% Dollar \$ Percent \% Ampersand \& +%% Acute accent \' Left paren \( Right paren \) +%% Asterisk \* Plus \+ Comma \, +%% Minus \- Point \. Solidus \/ +%% Colon \: Semicolon \; Less than \< +%% Equals \= Greater than \> Question mark \? +%% Commercial at \@ Left bracket \[ Backslash \\ +%% Right bracket \] Circumflex \^ Underscore \_ +%% Grave accent \` Left brace \{ Vertical bar \| +%% Right brace \} Tilde \~} +%% +\NeedsTeXFormat{LaTeX2e}[1996/12/01] +\ProvidesClass{flashcards}[2000/03/14 0.1.1 ([email protected])] +\RequirePackage{ifthen} +\RequirePackage[paper=letterpaper]{geometry} +\LoadClass{article} +\newboolean{flashcards@dvips}\setboolean{flashcards@dvips}{false} +\newboolean{flashcards@grid}\setboolean{flashcards@grid}{false} +\newboolean{flashcards@frame}\setboolean{flashcards@frame}{false} +\newboolean{flashcards@fronts}\setboolean{flashcards@fronts}{true} +\newboolean{flashcards@backs}\setboolean{flashcards@backs}{true} +\newlength{\cardheight} +\newlength{\cardwidth} +\newlength{\topoffset} +\newlength{\oddoffset} +\newlength{\evenoffset} +\newlength{\oddevenshift} +\newlength{\cardmargin} +\newlength{\cardinnerheight} +\newlength{\cardinnerwidth} +\DeclareOption{dvips}{ + \setboolean{flashcards@dvips}{true}} +\DeclareOption{grid}{ + \setboolean{flashcards@grid}{true}} +\DeclareOption{frame}{ + \setboolean{flashcards@frame}{true}} +\DeclareOption{fronts}{ + \setboolean{flashcards@backs}{false}} +\DeclareOption{backs}{ + \setboolean{flashcards@fronts}{false}} +\DeclareOption*{ + \InputIfFileExists{\CurrentOption.cfg}{}{ + \typeout{Coudln't find \CurrentOption.cfg, using defualt.} + \OptionNotUsed}} +\ProcessOptions +\pagestyle{empty} +\setlength{\oddevenshift}{\oddoffset} +\addtolength{\oddevenshift}{-\evenoffset} +\addtolength{\oddoffset}{-\oddevenshift} +\addtolength{\evenoffset}{\oddevenshift} +\geometry{compat2, + \cardpapermode, + \cardpaper, + top=\topoffset, + left=\oddoffset, + right=\evenoffset, + twosideshift=\oddevenshift, + bottom=0.0in, + noheadfoot} +\ifthenelse{\boolean{flashcards@dvips}}{\geometry{dvips}}{} +\newcounter{flashcards@row} +\newcounter{flashcards@col}[flashcards@row] +\ifthenelse{\boolean{flashcards@grid}} + {\newcommand{\flashcards@gridbox}[1]{% + \setlength{\fboxsep}{0in}\fbox{#1}} + \addtolength{\cardwidth}{-2\fboxrule} + \addtolength{\cardheight}{-2\fboxrule}} + {\newcommand{\flashcards@gridbox}[1]{#1}} +\ifthenelse{\boolean{flashcards@frame}} + {\newcommand{\flashcards@beginframebox}{% + \begin{tabular}{|@{\hspace*{\fboxsep}}c@{\hspace*{\fboxsep}}|}% + \hline}% + \newcommand{\flashcards@endframebox}{\\ \hline + \end{tabular}}} + {\newcommand{\flashcards@beginframebox}{}% + \newcommand{\flashcards@endframebox}{}} +\whiledo{\value{flashcards@row} < \cardrows}{% + \stepcounter{flashcards@row}% + \whiledo{\value{flashcards@col} < \cardcolumns}{% + \stepcounter{flashcards@col}% + \expandafter\newsavebox + \csname flashcardFrontR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \global\expandafter\setbox% + \csname flashcardFrontR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \hbox{\flashcards@gridbox{% + \parbox[t][\cardheight] + [c]{\cardwidth}% + {\rule{\cardwidth}{0pt}% + \rule{0pt}{\cardheight}}}}% + \expandafter\newsavebox + \csname flashcardBackR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \global\expandafter\setbox% + \csname flashcardBackR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \hbox{\flashcards@gridbox{% + \parbox[t][\cardheight] + [c]{\cardwidth}% + {\rule{\cardwidth}{0pt}% + \rule{0pt}{\cardheight}}}}% + } +} +\setcounter{flashcards@row}{1} +\setcounter{flashcards@col}{1} +\newcommand{\flashcards@frontfoot}{} +\newcommand{\flashcards@ps@front@empty}[3]{\@gobble{#1}\@gobble{#2}% + \flashcards@format@front#3} +\newcommand{\flashcards@ps@front@plain}[3]{\@gobble{#1}\@gobble{#2}% + \vspace*{\fill}\par% + \begin{center}\flashcards@format@front#3\end{center}% + \par\vspace*{\fill}} +\newcommand{\flashcards@ps@front@headings}[3]{% + {\flashcards@ps@front@head{\flashcards@format@front@head#2}}\par% + \vspace*{\fill}\begin{center}\flashcards@format@front#3\end{center}% + \vspace*{\fill}% + {\flashcards@ps@front@foot{\flashcards@format@front@foot#1}\par% + \vspace*{\fboxsep}}% +} +\newcommand{\flashcards@ps@back@begin@empty}{\flashcards@format@back} +\newcommand{\flashcards@ps@back@end@emtpy}{} +\newcommand{\flashcards@ps@back@begin@plain} + {\vspace*{\fill}\center\flashcards@format@back} +\newcommand{\flashcards@ps@back@end@plain}{\vspace*{\fill}} +\newcommand{\flashcards@ps@front@head@left}[1]{#1} +\newcommand{\flashcards@ps@front@head@right}[1]{\hspace*{\fill}#1} +\newcommand{\flashcards@ps@front@head@center}[1]{\centerline{#1}} +\newcommand{\flashcards@ps@front@foot@left}[1]{#1} +\newcommand{\flashcards@ps@front@foot@right}[1]{\hspace*{\fill}#1} +\newcommand{\flashcards@ps@front@foot@center}[1]{\centerline{#1}} +\newcommand{\flashcards@ps@front} + {\flashcards@ps@front@plain} +\newcommand{\flashcards@ps@front@head} + {\flashcards@ps@front@head@left} +\newcommand{\flashcards@ps@front@foot} + {\flashcards@ps@front@foot@right} +\newcommand{\flashcards@ps@back@begin} + {\flashcards@ps@back@begin@plain} +\newcommand{\flashcards@ps@back@end} + {\flashcards@ps@back@end@plain} +\newlength{\flashcards@savelineskip} +\newcommand{\flashcards@lineskip@zero} + {\setlength{\flashcards@savelineskip}{\lineskip}% + \setlength{\lineskip}{0pt}} +\newcommand{\flashcards@lineskip@restore} + {\setlength{\lineskip}{\flashcards@savelineskip}} +\newcommand{\flashcards@format@front} + {\large\bfseries} +\newcommand{\flashcards@format@front@head} + {\normalsize\scshape} +\newcommand{\flashcards@format@front@foot} + {\normalsize\scshape} +\newcommand{\flashcards@format@back}{} +\setlength{\cardmargin}{0.035\cardwidth} +\newcommand{\flashcards@flush} + {\flashcards@flushfronts\flashcards@flushbacks} +\ifthenelse{\boolean{flashcards@fronts}}{% + \newcommand{\flashcards@flushfronts}{% + \flashcards@lineskip@zero% + \noindent\raggedright\par% + \setcounter{flashcards@row}{0} + \whiledo{\value{flashcards@row} < \cardrows}{% + \stepcounter{flashcards@row}% + \whiledo{\value{flashcards@col} < \cardcolumns}{% + \stepcounter{flashcards@col}% + \flashcards@gridbox{\usebox{% + \csname flashcardFrontR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname}}% + \global\expandafter\setbox% + \csname flashcardFrontR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \hbox{\flashcards@gridbox{% + \parbox[t][\cardheight] + [c]{\cardwidth}% + {\rule{\cardwidth}{0pt}% + \rule{0pt}{\cardheight}}}}% + } + \noindent\raggedright\par% + } + \clearpage% + \flashcards@lineskip@restore% + \setcounter{flashcards@row}{1}% + \setcounter{flashcards@col}{1}% + } +}{% + \newcommand{\flashcards@flushfronts}{}% +} +\ifthenelse{\boolean{flashcards@backs}}{% + \newcommand{\flashcards@flushbacks}{% + \flashcards@lineskip@zero% + \noindent\raggedright\par% + \setcounter{flashcards@row}{0} + \whiledo{\value{flashcards@row} < \cardrows}{% + \stepcounter{flashcards@row}% + \setcounter{flashcards@col}{\cardcolumns} + \whiledo{\value{flashcards@col} > 0}{% + \flashcards@gridbox{\usebox{% + \csname flashcardBackR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname}}% + \global\expandafter\setbox + \csname flashcardBackR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \hbox{\flashcards@gridbox{% + \parbox[t][\cardheight] + [c]{\cardwidth}% + {\rule{\cardwidth}{0pt}% + \rule{0pt}{\cardheight}}}}% + \addtocounter{flashcards@col}{-1}% + } + \noindent\raggedright\par% + } + \clearpage% + \flashcards@lineskip@restore% + \setcounter{flashcards@row}{1}% + \setcounter{flashcards@col}{1}% + } +}{% + \newcommand{\flashcards@flushbacks}{}% +} +\AtEndDocument{% + \ifthenelse{\value{flashcards@row} = 1}{% + \ifthenelse{\value{flashcards@col} = 1}{}{% + \flashcards@flush}}{\flashcards@flush}% +} +\newcommand{\cardfrontstyle}[2][] + {\renewcommand{\flashcards@ps@front} + {\csname flashcards@ps@front@#2\endcsname} + \ifthenelse{\equal{#1}{}}{}{% + \renewcommand{\flashcards@format@front}{#1}}} +\newcommand{\cardbackstyle}[2][] + {\renewcommand{\flashcards@ps@back@begin} + {\csname flashcards@ps@back@begin@#2\endcsname} + \renewcommand{\flashcards@ps@back@end} + {\csname flashcards@ps@back@end@#2\endcsname} + \ifthenelse{\equal{#1}{}}{}{% + \renewcommand{\flashcards@format@back}{#1}}} +\newcommand{\cardfrontheadstyle}[2][] + {\renewcommand{\flashcards@ps@front@head} + {\csname flashcards@ps@front@head@#2\endcsname} + \ifthenelse{\equal{#1}{}}{}{% + \renewcommand{\flashcards@format@front@head}{#1}}} +\newcommand{\cardfrontfootstyle}[2][] + {\renewcommand{\flashcards@ps@front@foot} + {\csname flashcards@ps@front@foot@#2\endcsname} + \ifthenelse{\equal{#1}{}}{}{% + \renewcommand{\flashcards@format@front@foot}{#1}}} +\newcommand{\cardfrontfoot}[1] + {\renewcommand{\flashcards@frontfoot}{#1}} +\newenvironment{flashcard}[2][]{% + \setlength{\cardinnerwidth}{\cardwidth}% + \addtolength{\cardinnerwidth}{-2\cardmargin}% + \setlength{\cardinnerheight}{\cardheight}% + \addtolength{\cardinnerheight}{-2\cardmargin}% + \ifthenelse{\boolean{flashcards@fronts}}{% + \global\expandafter\setbox% + \csname flashcardFrontR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \hbox{\begingroup\aftergroup}% + \begin{minipage}[t][\cardheight] + [c]{\cardwidth}% + \begin{center}% + \flashcards@beginframebox% + \begin{minipage}[t][\cardinnerheight] + [t]{\cardinnerwidth}% + \flashcards@ps@front{\flashcards@frontfoot}{#1}{#2}% + \end{minipage}% + \flashcards@endframebox% + \end{center}% + \end{minipage}% + \endgroup% + }{\@gobble{#1}}% + \global\expandafter\setbox% + \csname flashcardBackR\roman{flashcards@row}% + C\roman{flashcards@col}\endcsname% + \hbox{\begingroup\aftergroup}% + \begin{minipage}[t][\cardheight] + [c]{\cardwidth}% + \begin{center}% + \flashcards@beginframebox% + \begin{minipage}[t][\cardinnerheight] + [t]{\cardinnerwidth}% + \flashcards@ps@back@begin% +}{% + \flashcards@ps@back@end% + \end{minipage}% + \flashcards@endframebox% + \end{center}% + \end{minipage}% + \endgroup% + \stepcounter{flashcards@col}% + \ifthenelse{\value{flashcards@col} > \cardcolumns}{% + \stepcounter{flashcards@row}% + \ifthenelse{\value{flashcards@row} > \cardrows}{% + \flashcards@flush% + }{% + \setcounter{flashcards@col}{1}% + }% + }{}% +} + +\endinput +%% +%% End of file `flashcards.cls'.
anarchivist/tildebin
c266f11acb56bb1a2dc505612d5c6d8a4e060761
switch_tsk.sh: switch the version of sleuthkit under homebrew
diff --git a/switch_tsk.sh b/switch_tsk.sh new file mode 100755 index 0000000..46887da --- /dev/null +++ b/switch_tsk.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +if [ $# -lt 1 ] +then + echo "Usage : $0 <version | current>" + exit +fi + +case "$1" in + +current) brew info sleuthkit | grep \\*$ + ;; +3.2.3) brew switch sleuthkit 3.2.3 + brew link fiwalk + ;; +4.0.0) brew unlink fiwalk + brew switch sleuthkit 4.0.0 + ;; +4.0.1) brew unlink fiwalk + brew switch sleuthkit 4.0.1 + ;; +# assumes HEAD is a27fd4b782a5a6d8c2e1525f5fdfb0df20291f1c or after +HEAD) brew unlink fiwalk + brew switch sleuthkit HEAD + ;; + +esac \ No newline at end of file
anarchivist/tildebin
5824363e5fd2f34a0681f1a371d0bd805cc85427
add greptabulator
diff --git a/greptabulator b/greptabulator new file mode 100755 index 0000000..b41160a --- /dev/null +++ b/greptabulator @@ -0,0 +1,4 @@ +#!/bin/bash +# greptabulator.sh [expression] [directory] +grep -hR $1 $2 | sort | uniq -c | sort -nr | \ +awk '{typesum += 1; matchsum += $1; print} END {print typesum, "unique types"; print matchsum, "total matches"}' typesum=0 matchsum=0
anarchivist/tildebin
ce1ee4ec5cfe9b7685c02e54a26952f78b465b5e
added ttfmify
diff --git a/README.textile b/README.textile index 98e084e..8069083 100644 --- a/README.textile +++ b/README.textile @@ -1,12 +1,13 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. * Blame "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist h2. Possibly incomplete list of scripts and what they do * marcstats: get statistics on files containing MARC records (from "this gist":http://gist.github.com/262826 ) * osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. * svn-authorsfile: generate a skeletal git-svn authorsfile from an svn commit log +* ttfmify: create an MP3 from an M4A for "turntable.fm":http://turntable.fm * yale-apartments-feed: generate an RSS feed from Yale's off-campus housing ads diff --git a/ttfmify b/ttfmify new file mode 100755 index 0000000..f608de9 --- /dev/null +++ b/ttfmify @@ -0,0 +1,26 @@ +#!/bin/bash +# make an mp3 out of an AAC file + +if [ $# -ne 1 ] + then + echo "`basename $0` <m4afile> - create an MP3 from AAC/M4A and transfer metadata" + exit 2 +fi + +FAAD="`which faad`" +LAME="`which lame`" + +# collect metadata + +TITLE="`$FAAD -i "$1" 2>&1 | grep title:\ | sed -e 's/.*title: //g'`" +ARTIST="`$FAAD -i "$1" 2>&1 | grep artist:\ | sed -e 's/.*artist: //g'`" +ALBUM="`$FAAD -i "$1" 2>&1 | grep album:\ | sed -e 's/.*album: //g'`" +GENRE="`$FAAD -i "$1" 2>&1 | grep genre:\ | sed -e 's/.*genre: //g'`" +TRACKNUM="`$FAAD -i "$1" 2>&1 | grep track:\ | sed -e 's/.*track: //g'`" +TRACKOF="`$FAAD -i "$1" 2>&1 | grep totaltracks:\ | sed -e 's/.*totaltracks: //g'`" + +$FAAD -q -o - "$1" | $LAME --silent --tt "$TITLE" --ta "$ARTIST" --tl "$ALBUM" --tg "$GENRE" --tn $TRACKNUM/$TRACKOF - "/tmp/`basename "$1" .m4a`.mp3" + +echo "/tmp/`basename "$1" .m4a`.mp3" + +exit 1 \ No newline at end of file
anarchivist/tildebin
78dd0d47b35f07904328fd89a670418c90264395
Remove ack and mount-fedora-image
diff --git a/README.textile b/README.textile index 070659d..98e084e 100644 --- a/README.textile +++ b/README.textile @@ -1,15 +1,12 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. * Blame "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist h2. Possibly incomplete list of scripts and what they do -* ack: Standalone version of "ack, the grep replacement":http://github.com/petdance/ack -* fits: Launch "FITS, the file information toolset":http://code.google.com/p/fits/ * marcstats: get statistics on files containing MARC records (from "this gist":http://gist.github.com/262826 ) -* mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image * osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. * svn-authorsfile: generate a skeletal git-svn authorsfile from an svn commit log -* yale-apartments-feed: generate an RSS feed from Yale's off-campus housing ads \ No newline at end of file +* yale-apartments-feed: generate an RSS feed from Yale's off-campus housing ads diff --git a/ack b/ack deleted file mode 100755 index 7cc459c..0000000 --- a/ack +++ /dev/null @@ -1,2624 +0,0 @@ -#!/usr/bin/env perl -# -# This file, ack, is generated code. -# Please DO NOT EDIT or send patches for it. -# -# Please take a look at the source from -# http://github.com/petdance/ack -# and submit patches against the individual files -# that build ack. -# - -use warnings; -use strict; - -our $VERSION = '1.92'; -# Check http://betterthangrep.com/ for updates - -# These are all our globals. - - -MAIN: { - if ( $App::Ack::VERSION ne $main::VERSION ) { - App::Ack::die( "Program/library version mismatch\n\t$0 is $main::VERSION\n\t$INC{'App/Ack.pm'} is $App::Ack::VERSION" ); - } - - # Do preliminary arg checking; - my $env_is_usable = 1; - for ( @ARGV ) { - last if ( $_ eq '--' ); - - # Priorities! Get the --thpppt checking out of the way. - /^--th[pt]+t+$/ && App::Ack::_thpppt($_); - - # See if we want to ignore the environment. (Don't tell Al Gore.) - if ( $_ eq '--noenv' ) { - my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV ); - delete @ENV{@keys}; - $env_is_usable = 0; - } - } - unshift( @ARGV, App::Ack::read_ackrc() ) if $env_is_usable; - App::Ack::load_colors(); - - if ( exists $ENV{ACK_SWITCHES} ) { - App::Ack::warn( 'ACK_SWITCHES is no longer supported. Use ACK_OPTIONS.' ); - } - - if ( !@ARGV ) { - App::Ack::show_help(); - exit 1; - } - - main(); -} - -sub main { - my $opt = App::Ack::get_command_line_options(); - - $| = 1 if $opt->{flush}; # Unbuffer the output if flush mode - - if ( App::Ack::input_from_pipe() ) { - # We're going into filter mode - for ( qw( f g l ) ) { - $opt->{$_} and App::Ack::die( "Can't use -$_ when acting as a filter." ); - } - $opt->{show_filename} = 0; - $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt ); - if ( my $nargs = @ARGV ) { - my $s = $nargs == 1 ? '' : 's'; - App::Ack::warn( "Ignoring $nargs argument$s on the command-line while acting as a filter." ); - } - my $res = App::Ack::Resource::Basic->new( '-' ); - App::Ack::search_resource( $res, $opt ); - $res->close(); - exit 0; - } - - my $file_matching = $opt->{f} || $opt->{lines}; - if ( !$file_matching ) { - @ARGV or App::Ack::die( 'No regular expression found.' ); - $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt ); - } - - # check that all regexes do compile fine - App::Ack::check_regex( $_ ) for ( $opt->{regex}, $opt->{G} ); - - my $what = App::Ack::get_starting_points( \@ARGV, $opt ); - my $iter = App::Ack::get_iterator( $what, $opt ); - App::Ack::filetype_setup(); - - my $nmatches = 0; - - App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager}; - if ( $opt->{f} ) { - $nmatches = App::Ack::print_files( $iter, $opt ); - } - elsif ( $opt->{l} || $opt->{count} ) { - $nmatches = App::Ack::print_files_with_matches( $iter, $opt ); - } - else { - $nmatches = App::Ack::print_matches( $iter, $opt ); - } - close $App::Ack::fh; - exit ($nmatches ? 0 : 1); -} - -=head1 NAME - -ack - grep-like text finder - -=head1 SYNOPSIS - - ack [options] PATTERN [FILE...] - ack -f [options] [DIRECTORY...] - -=head1 DESCRIPTION - -Ack is designed as a replacement for 99% of the uses of F<grep>. - -Ack searches the named input FILEs (or standard input if no files are -named, or the file name - is given) for lines containing a match to the -given PATTERN. By default, ack prints the matching lines. - -Ack can also list files that would be searched, without actually searching -them, to let you take advantage of ack's file-type filtering capabilities. - -=head1 FILE SELECTION - -I<ack> is intelligent about the files it searches. It knows about -certain file types, based on both the extension on the file and, -in some cases, the contents of the file. These selections can be -made with the B<--type> option. - -With no file selections, I<ack> only searches files of types that -it recognizes. If you have a file called F<foo.wango>, and I<ack> -doesn't know what a .wango file is, I<ack> won't search it. - -The B<-a> option tells I<ack> to select all files, regardless of -type. - -Some files will never be selected by I<ack>, even with B<-a>, -including: - -=over 4 - -=item * Backup files: Files matching F<#*#> or ending with F<~>. - -=item * Coredumps: Files matching F<core.\d+> - -=back - -However, I<ack> always searches the files given on the command line, -no matter what type. Furthermore, by specifying the B<-u> option all -files will be searched. - -=head1 DIRECTORY SELECTION - -I<ack> descends through the directory tree of the starting directories -specified. However, it will ignore the shadow directories used by -many version control systems, and the build directories used by the -Perl MakeMaker system. You may add or remove a directory from this -list with the B<--[no]ignore-dir> option. The option may be repeated -to add/remove multiple directories from the ignore list. - -For a complete list of directories that do not get searched, run -F<ack --help>. - -=head1 WHEN TO USE GREP - -I<ack> trumps I<grep> as an everyday tool 99% of the time, but don't -throw I<grep> away, because there are times you'll still need it. - -E.g., searching through huge files looking for regexes that can be -expressed with I<grep> syntax should be quicker with I<grep>. - -If your script or parent program uses I<grep> C<--quiet> or -C<--silent> or needs exit 2 on IO error, use I<grep>. - -=head1 OPTIONS - -=over 4 - -=item B<-a>, B<--all> - -Operate on all files, regardless of type (but still skip directories -like F<blib>, F<CVS>, etc.) - -=item B<-A I<NUM>>, B<--after-context=I<NUM>> - -Print I<NUM> lines of trailing context after matching lines. - -=item B<-B I<NUM>>, B<--before-context=I<NUM>> - -Print I<NUM> lines of leading context before matching lines. - -=item B<-C [I<NUM>]>, B<--context[=I<NUM>]> - -Print I<NUM> lines (default 2) of context around matching lines. - -=item B<-c>, B<--count> - -Suppress normal output; instead print a count of matching lines for -each input file. If B<-l> is in effect, it will only show the -number of lines for each file that has lines matching. Without -B<-l>, some line counts may be zeroes. - -=item B<--color>, B<--nocolor> - -B<--color> highlights the matching text. B<--nocolor> supresses -the color. This is on by default unless the output is redirected. - -On Windows, this option is off by default unless the -L<Win32::Console::ANSI> module is installed or the C<ACK_PAGER_COLOR> -environment variable is used. - -=item B<--color-filename=I<color>> - -Sets the color to be used for filenames. - -=item B<--color-match=I<color>> - -Sets the color to be used for matches. - -=item B<--column> - -Show the column number of the first match. This is helpful for editors -that can place your cursor at a given position. - -=item B<--env>, B<--noenv> - -B<--noenv> disables all environment processing. No F<.ackrc> is read -and all environment variables are ignored. By default, F<ack> considers -F<.ackrc> and settings in the environment. - -=item B<--flush> - -B<--flush> flushes output immediately. This is off by default -unless ack is running interactively (when output goes to a pipe -or file). - -=item B<-f> - -Only print the files that would be searched, without actually doing -any searching. PATTERN must not be specified, or it will be taken as -a path to search. - -=item B<--follow>, B<--nofollow> - -Follow or don't follow symlinks, other than whatever starting files -or directories were specified on the command line. - -This is off by default. - -=item B<-G I<REGEX>> - -Only paths matching I<REGEX> are included in the search. The entire -path and filename are matched against I<REGEX>, and I<REGEX> is a -Perl regular expression, not a shell glob. - -The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I<REGEX>. - -=item B<-g I<REGEX>> - -Print files where the relative path + filename matches I<REGEX>. This option is -a convenience shortcut for B<-f> B<-G I<REGEX>>. - -The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I<REGEX>. - -=item B<--group>, B<--nogroup> - -B<--group> groups matches by file name with. This is the default when -used interactively. - -B<--nogroup> prints one result per line, like grep. This is the default -when output is redirected. - -=item B<-H>, B<--with-filename> - -Print the filename for each match. - -=item B<-h>, B<--no-filename> - -Suppress the prefixing of filenames on output when multiple files are -searched. - -=item B<--help> - -Print a short help statement. - -=item B<-i>, B<--ignore-case> - -Ignore case in the search strings. - -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. - -=item B<--[no]ignore-dir=DIRNAME> - -Ignore directory (as CVS, .svn, etc are ignored). May be used multiple times -to ignore multiple directories. For example, mason users may wish to include -B<--ignore-dir=data>. The B<--noignore-dir> option allows users to search -directories which would normally be ignored (perhaps to research the contents -of F<.svn/props> directories). - -=item B<--line=I<NUM>> - -Only print line I<NUM> of each file. Multiple lines can be given with multiple -B<--line> options or as a comma separated list (B<--line=3,5,7>). B<--line=4-7> -also works. The lines are always output in ascending order, no matter the -order given on the command line. - -=item B<-l>, B<--files-with-matches> - -Only print the filenames of matching files, instead of the matching text. - -=item B<-L>, B<--files-without-matches> - -Only print the filenames of files that do I<NOT> match. This is equivalent -to specifying B<-l> and B<-v>. - -=item B<--match I<REGEX>> - -Specify the I<REGEX> explicitly. This is helpful if you don't want to put the -regex as your first argument, e.g. when executing multiple searches over the -same set of files. - - # search for foo and bar in given files - ack file1 t/file* --match foo - ack file1 t/file* --match bar - -=item B<-m=I<NUM>>, B<--max-count=I<NUM>> - -Stop reading a file after I<NUM> matches. - -=item B<--man> - -Print this manual page. - -=item B<-n> - -No descending into subdirectories. - -=item B<-o> - -Show only the part of each line matching PATTERN (turns off text -highlighting) - -=item B<--output=I<expr>> - -Output the evaluation of I<expr> for each line (turns off text -highlighting) - -=item B<--pager=I<program>> - -Direct ack's output through I<program>. This can also be specified -via the C<ACK_PAGER> and C<ACK_PAGER_COLOR> environment variables. - -Using --pager does not suppress grouping and coloring like piping -output on the command-line does. - -=item B<--passthru> - -Prints all lines, whether or not they match the expression. Highlighting -will still work, though, so it can be used to highlight matches while -still seeing the entire file, as in: - - # Watch a log file, and highlight a certain IP address - $ tail -f ~/access.log | ack --passthru 123.45.67.89 - -=item B<--print0> - -Only works in conjunction with -f, -g, -l or -c (filename output). The filenames -are output separated with a null byte instead of the usual newline. This is -helpful when dealing with filenames that contain whitespace, e.g. - - # remove all files of type html - ack -f --html --print0 | xargs -0 rm -f - -=item B<-Q>, B<--literal> - -Quote all metacharacters in PATTERN, it is treated as a literal. - -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. - -=item B<--smart-case>, B<--no-smart-case> - -Ignore case in the search strings if PATTERN contains no uppercase -characters. This is similar to C<smartcase> in vim. This option is -off by default. - -B<-i> always overrides this option. - -This applies only to the PATTERN, not to the regexes given for the -B<-g> and B<-G> options. - -=item B<--sort-files> - -Sorts the found files lexically. Use this if you want your file -listings to be deterministic between runs of I<ack>. - -=item B<--thpppt> - -Display the all-important Bill The Cat logo. Note that the exact -spelling of B<--thpppppt> is not important. It's checked against -a regular expression. - -=item B<--type=TYPE>, B<--type=noTYPE> - -Specify the types of files to include or exclude from a search. -TYPE is a filetype, like I<perl> or I<xml>. B<--type=perl> can -also be specified as B<--perl>, and B<--type=noperl> can be done -as B<--noperl>. - -If a file is of both type "foo" and "bar", specifying --foo and ---nobar will exclude the file, because an exclusion takes precedence -over an inclusion. - -Type specifications can be repeated and are ORed together. - -See I<ack --help=types> for a list of valid types. - -=item B<--type-add I<TYPE>=I<.EXTENSION>[,I<.EXT2>[,...]]> - -Files with the given EXTENSION(s) are recognized as being of (the -existing) type TYPE. See also L</"Defining your own types">. - - -=item B<--type-set I<TYPE>=I<.EXTENSION>[,I<.EXT2>[,...]]> - -Files with the given EXTENSION(s) are recognized as being of type -TYPE. This replaces an existing definition for type TYPE. See also -L</"Defining your own types">. - -=item B<-u>, B<--unrestricted> - -All files and directories (including blib/, core.*, ...) are searched, -nothing is skipped. When both B<-u> and B<--ignore-dir> are used, the -B<--ignore-dir> option has no effect. - -=item B<-v>, B<--invert-match> - -Invert match: select non-matching lines - -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. - -=item B<--version> - -Display version and copyright information. - -=item B<-w>, B<--word-regexp> - -Force PATTERN to match only whole words. The PATTERN is wrapped with -C<\b> metacharacters. - -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. - -=item B<-1> - -Stops after reporting first match of any kind. This is different -from B<--max-count=1> or B<-m1>, where only one match per file is -shown. Also, B<-1> works with B<-f> and B<-g>, where B<-m> does -not. - -=back - -=head1 THE .ackrc FILE - -The F<.ackrc> file contains command-line options that are prepended -to the command line before processing. Multiple options may live -on multiple lines. Lines beginning with a # are ignored. A F<.ackrc> -might look like this: - - # Always sort the files - --sort-files - - # Always color, even if piping to a another program - --color - - # Use "less -r" as my pager - --pager=less -r - -Note that arguments with spaces in them do not need to be quoted, -as they are not interpreted by the shell. Basically, each I<line> -in the F<.ackrc> file is interpreted as one element of C<@ARGV>. - -F<ack> looks in your home directory for the F<.ackrc>. You can -specify another location with the F<ACKRC> variable, below. - -If B<--noenv> is specified on the command line, the F<.ackrc> file -is ignored. - -=head1 Defining your own types - -ack allows you to define your own types in addition to the predefined -types. This is done with command line options that are best put into -an F<.ackrc> file - then you do not have to define your types over and -over again. In the following examples the options will always be shown -on one command line so that they can be easily copy & pasted. - -I<ack --perl foo> searches for foo in all perl files. I<ack --help=types> -tells you, that perl files are files ending -in .pl, .pm, .pod or .t. So what if you would like to include .xs -files as well when searching for --perl files? I<ack --type-add perl=.xs --perl foo> -does this for you. B<--type-add> appends -additional extensions to an existing type. - -If you want to define a new type, or completely redefine an existing -type, then use B<--type-set>. I<ack --type-set -eiffel=.e,.eiffel> defines the type I<eiffel> to include files with -the extensions .e or .eiffel. So to search for all eiffel files -containing the word Bertrand use I<ack --type-set eiffel=.e,.eiffel --eiffel Bertrand>. -As usual, you can also write B<--type=eiffel> -instead of B<--eiffel>. Negation also works, so B<--noeiffel> excludes -all eiffel files from a search. Redefining also works: I<ack --type-set cc=.c,.h> -and I<.xs> files no longer belong to the type I<cc>. - -When defining your own types in the F<.ackrc> file you have to use -the following: - - --type-set=eiffel=.e,.eiffel - -or writing on separate lines - - --type-set - eiffel=.e,.eiffel - -The following does B<NOT> work in the F<.ackrc> file: - - --type-set eiffel=.e,.eiffel - - -In order to see all currently defined types, use I<--help types>, e.g. -I<ack --type-set backup=.bak --type-add perl=.perl --help types> - -Restrictions: - -=over 4 - -=item - -The types 'skipped', 'make', 'binary' and 'text' are considered "builtin" and -cannot be altered. - -=item - -The shebang line recognition of the types 'perl', 'ruby', 'php', 'python', -'shell' and 'xml' cannot be redefined by I<--type-set>, it is always -active. However, the shebang line is only examined for files where the -extension is not recognised. Therefore it is possible to say -I<ack --type-set perl=.perl --type-set foo=.pl,.pm,.pod,.t --perl --nofoo> and -only find your shiny new I<.perl> files (and all files with unrecognized extension -and perl on the shebang line). - -=back - -=head1 ENVIRONMENT VARIABLES - -For commonly-used ack options, environment variables can make life much easier. -These variables are ignored if B<--noenv> is specified on the command line. - -=over 4 - -=item ACKRC - -Specifies the location of the F<.ackrc> file. If this file doesn't -exist, F<ack> looks in the default location. - -=item ACK_OPTIONS - -This variable specifies default options to be placed in front of -any explicit options on the command line. - -=item ACK_COLOR_FILENAME - -Specifies the color of the filename when it's printed in B<--group> -mode. By default, it's "bold green". - -The recognized attributes are clear, reset, dark, bold, underline, -underscore, blink, reverse, concealed black, red, green, yellow, -blue, magenta, on_black, on_red, on_green, on_yellow, on_blue, -on_magenta, on_cyan, and on_white. Case is not significant. -Underline and underscore are equivalent, as are clear and reset. -The color alone sets the foreground color, and on_color sets the -background color. - -This option can also be set with B<--color-filename>. - -=item ACK_COLOR_MATCH - -Specifies the color of the matching text when printed in B<--color> -mode. By default, it's "black on_yellow". - -This option can also be set with B<--color-match>. - -See B<ACK_COLOR_FILENAME> for the color specifications. - -=item ACK_PAGER - -Specifies a pager program, such as C<more>, C<less> or C<most>, to which -ack will send its output. - -Using C<ACK_PAGER> does not suppress grouping and coloring like -piping output on the command-line does, except that on Windows -ack will assume that C<ACK_PAGER> does not support color. - -C<ACK_PAGER_COLOR> overrides C<ACK_PAGER> if both are specified. - -=item ACK_PAGER_COLOR - -Specifies a pager program that understands ANSI color sequences. -Using C<ACK_PAGER_COLOR> does not suppress grouping and coloring -like piping output on the command-line does. - -If you are not on Windows, you never need to use C<ACK_PAGER_COLOR>. - -=back - -=head1 ACK & OTHER TOOLS - -=head2 Vim integration - -F<ack> integrates easily with the Vim text editor. Set this in your -F<.vimrc> to use F<ack> instead of F<grep>: - - set grepprg=ack\ -a - -That examples uses C<-a> to search through all files, but you may -use other default flags. Now you can search with F<ack> and easily -step through the results in Vim: - - :grep Dumper perllib - -=head2 Emacs integration - -Phil Jackson put together an F<ack.el> extension that "provides a -simple compilation mode ... has the ability to guess what files you -want to search for based on the major-mode." - -L<http://www.shellarchive.co.uk/content/emacs.html> - -=head2 TextMate integration - -Pedro Melo is a TextMate user who writes "I spend my day mostly -inside TextMate, and the built-in find-in-project sucks with large -projects. So I hacked a TextMate command that was using find + -grep to use ack. The result is the Search in Project with ack, and -you can find it here: -L<http://www.simplicidade.org/notes/archives/2008/03/search_in_proje.html>" - -=head2 Shell and Return Code - -For greater compatibility with I<grep>, I<ack> in normal use returns -shell return or exit code of 0 only if something is found and 1 if -no match is found. - -(Shell exit code 1 is C<$?=256> in perl with C<system> or backticks.) - -The I<grep> code 2 for errors is not used. - -If C<-f> or C<-g> are specified, then 0 is returned if at least one -file is found. If no files are found, then 1 is returned. - -=cut - -=head1 DEBUGGING ACK PROBLEMS - -If ack gives you output you're not expecting, start with a few simple steps. - -=head2 Use B<--noenv> - -Your environment variables and F<.ackrc> may be doing things you're -not expecting, or forgotten you specified. Use B<--noenv> to ignore -your environment and F<.ackrc>. - -=head2 Use B<-f> to see what files you're scanning - -The reason I created B<-f> in the first place was as a debugging -tool. If ack is not finding matches you think it should find, run -F<ack -f> to see what files are being checked. - -=head1 TIPS - -=head2 Use the F<.ackrc> file. - -The F<.ackrc> is the place to put all your options you use most of -the time but don't want to remember. Put all your --type-add and ---type-set definitions in it. If you like --smart-case, set it -there, too. I also set --sort-files there. - -=head2 Use F<-f> for working with big codesets - -Ack does more than search files. C<ack -f --perl> will create a -list of all the Perl files in a tree, ideal for sending into F<xargs>. -For example: - - # Change all "this" to "that" in all Perl files in a tree. - ack -f --perl | xargs perl -p -i -e's/this/that/g' - -or if you prefer: - - perl -p -i -e's/this/thatg/' $(ack -f --perl) - -=head2 Use F<-Q> when in doubt about metacharacters - -If you're searching for something with a regular expression -metacharacter, most often a period in a filename or IP address, add -the -Q to avoid false positives without all the backslashing. See -the following example for more... - -=head2 Use ack to watch log files - -Here's one I used the other day to find trouble spots for a website -visitor. The user had a problem loading F<troublesome.gif>, so I -took the access log and scanned it with ack twice. - - ack -Q aa.bb.cc.dd /path/to/access.log | ack -Q -B5 troublesome.gif - -The first ack finds only the lines in the Apache log for the given -IP. The second finds the match on my troublesome GIF, and shows -the previous five lines from the log in each case. - -=head2 Share your knowledge - -Join the ack-users mailing list. Send me your tips and I may add -them here. - -=head1 FAQ - -=head2 Why isn't ack finding a match in (some file)? - -Probably because it's of a type that ack doesn't recognize. - -ack's searching behavior is driven by filetype. If ack doesn't -know what kind of file it is, ack ignores it. - -If you want ack to search files that it doesn't recognize, use the -C<-a> switch. - -If you want ack to search every file, even ones that it always -ignores like coredumps and backup files, use the C<-u> switch. - -=head2 Why does ack ignore unknown files by default? - -ack is designed by a programmer, for programmers, for searching -large trees of code. Most codebases have a lot files in them which -aren't source files (like compiled object files, source control -metadata, etc), and grep wastes a lot of time searching through all -of those as well and returning matches from those files. - -That's why ack's behavior of not searching things it doesn't recognize -is one of its greatest strengths: the speed you get from only -searching the things that you want to be looking at. - -=head2 Wouldn't it be great if F<ack> did search & replace? - -No, ack will always be read-only. Perl has a perfectly good way -to do search & replace in files, using the C<-i>, C<-p> and C<-n> -switches. - -You can certainly use ack to select your files to update. For -example, to change all "foo" to "bar" in all PHP files, you can do -this form the Unix shell: - - $ perl -i -p -e's/foo/bar/g' $(ack -f --php) - -=head2 Can you make ack recognize F<.xyz> files? - -That's an enhancement. Please see the section in the manual about -enhancements. - -=head2 There's already a program/package called ack. - -Yes, I know. - -=head2 Why is it called ack if it's called ack-grep? - -The name of the program is "ack". Some packagers have called it -"ack-grep" when creating packages because there's already a package -out there called "ack" that has nothing to do with this ack. - -I suggest you rename your ack-grep install to "ack" because one of -the crucial benefits of ack is having a name that's so short and -simple to type. - -=head1 AUTHOR - -Andy Lester, C<< <andy at petdance.com> >> - -=head1 BUGS - -Please report any bugs or feature requests to the issues list at -Github: L<http://github.com/petdance/ack/issues> - -=head1 ENHANCEMENTS - -All enhancement requests MUST first be posted to the ack-users -mailing list at L<http://groups.google.com/group/ack-users>. I -will not consider a request without it first getting seen by other -ack users. This includes requests for new filetypes. - -There is a list of enhancements I want to make to F<ack> in the ack -issues list at Github: L<http://github.com/petdance/ack/issues> - -Patches are always welcome, but patches with tests get the most -attention. - -=head1 SUPPORT - -Support for and information about F<ack> can be found at: - -=over 4 - -=item * The ack homepage - -L<http://betterthangrep.com/> - -=item * The ack issues list at Github - -L<http://github.com/petdance/ack/issues> - -=item * AnnoCPAN: Annotated CPAN documentation - -L<http://annocpan.org/dist/ack> - -=item * CPAN Ratings - -L<http://cpanratings.perl.org/d/ack> - -=item * Search CPAN - -L<http://search.cpan.org/dist/ack> - -=item * Git source repository - -L<http://github.com/petdance/ack> - -=back - -=head1 ACKNOWLEDGEMENTS - -How appropriate to have I<ack>nowledgements! - -Thanks to everyone who has contributed to ack in any way, including -Packy Anderson, -JR Boyens, -Dan Sully, -Ryan Niebur, -Kent Fredric, -Mike Morearty, -Ingmar Vanhassel, -Eric Van Dewoestine, -Sitaram Chamarty, -Adam James, -Richard Carlsson, -Pedro Melo, -AJ Schuster, -Phil Jackson, -Michael Schwern, -Jan Dubois, -Christopher J. Madsen, -Matthew Wickline, -David Dyck, -Jason Porritt, -Jjgod Jiang, -Thomas Klausner, -Uri Guttman, -Peter Lewis, -Kevin Riggle, -Ori Avtalion, -Torsten Blix, -Nigel Metheringham, -GE<aacute>bor SzabE<oacute>, -Tod Hagan, -Michael Hendricks, -E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason, -Piers Cawley, -Stephen Steneker, -Elias Lutfallah, -Mark Leighton Fisher, -Matt Diephouse, -Christian Jaeger, -Bill Sully, -Bill Ricker, -David Golden, -Nilson Santos F. Jr, -Elliot Shank, -Merijn Broeren, -Uwe Voelker, -Rick Scott, -Ask BjE<oslash>rn Hansen, -Jerry Gay, -Will Coleda, -Mike O'Regan, -Slaven ReziE<0x107>, -Mark Stosberg, -David Alan Pisoni, -Adriano Ferreira, -James Keenan, -Leland Johnson, -Ricardo Signes -and Pete Krawczyk. - -=head1 COPYRIGHT & LICENSE - -Copyright 2005-2009 Andy Lester. - -This program is free software; you can redistribute it and/or modify -it under the terms of either: - -=over 4 - -=item * the GNU General Public License as published by the Free -Software Foundation; either version 1, or (at your option) any later -version, or - -=item * the Artistic License version 2.0. - -=back - -=cut -package File::Next; - -use strict; -use warnings; - - -our $VERSION = '1.06'; - - - -use File::Spec (); - - -our $name; # name of the current file -our $dir; # dir of the current file - -our %files_defaults; -our %skip_dirs; - -BEGIN { - %files_defaults = ( - file_filter => undef, - descend_filter => undef, - error_handler => sub { CORE::die @_ }, - sort_files => undef, - follow_symlinks => 1, - ); - %skip_dirs = map {($_,1)} (File::Spec->curdir, File::Spec->updir); -} - - -sub files { - ($_[0] eq __PACKAGE__) && die 'File::Next::files must not be invoked as File::Next->files'; - - my ($parms,@queue) = _setup( \%files_defaults, @_ ); - my $filter = $parms->{file_filter}; - - return sub { - while (@queue) { - my ($dir,$file,$fullpath) = splice( @queue, 0, 3 ); - if ( -f $fullpath ) { - if ( $filter ) { - local $_ = $file; - local $File::Next::dir = $dir; - local $File::Next::name = $fullpath; - next if not $filter->(); - } - return wantarray ? ($dir,$file,$fullpath) : $fullpath; - } - elsif ( -d _ ) { - unshift( @queue, _candidate_files( $parms, $fullpath ) ); - } - } # while - - return; - }; # iterator -} - - - - - - - -sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] } -sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] } - -sub reslash { - my $path = shift; - - my @parts = split( /\//, $path ); - - return $path if @parts < 2; - - return File::Spec->catfile( @parts ); -} - - - -sub _setup { - my $defaults = shift; - my $passed_parms = ref $_[0] eq 'HASH' ? {%{+shift}} : {}; # copy parm hash - - my %passed_parms = %{$passed_parms}; - - my $parms = {}; - for my $key ( keys %{$defaults} ) { - $parms->{$key} = - exists $passed_parms{$key} - ? delete $passed_parms{$key} - : $defaults->{$key}; - } - - # Any leftover keys are bogus - for my $badkey ( keys %passed_parms ) { - my $sub = (caller(1))[3]; - $parms->{error_handler}->( "Invalid option passed to $sub(): $badkey" ); - } - - # If it's not a code ref, assume standard sort - if ( $parms->{sort_files} && ( ref($parms->{sort_files}) ne 'CODE' ) ) { - $parms->{sort_files} = \&sort_standard; - } - my @queue; - - for ( @_ ) { - my $start = reslash( $_ ); - if (-d $start) { - push @queue, ($start,undef,$start); - } - else { - push @queue, (undef,$start,$start); - } - } - - return ($parms,@queue); -} - - -sub _candidate_files { - my $parms = shift; - my $dir = shift; - - my $dh; - if ( !opendir $dh, $dir ) { - $parms->{error_handler}->( "$dir: $!" ); - return; - } - - my @newfiles; - my $descend_filter = $parms->{descend_filter}; - my $follow_symlinks = $parms->{follow_symlinks}; - my $sort_sub = $parms->{sort_files}; - - for my $file ( grep { !exists $skip_dirs{$_} } readdir $dh ) { - my $has_stat; - - # Only do directory checking if we have a descend_filter - my $fullpath = File::Spec->catdir( $dir, $file ); - if ( !$follow_symlinks ) { - next if -l $fullpath; - $has_stat = 1; - } - - if ( $descend_filter ) { - if ( $has_stat ? (-d _) : (-d $fullpath) ) { - local $File::Next::dir = $fullpath; - local $_ = $file; - next if not $descend_filter->(); - } - } - if ( $sort_sub ) { - push( @newfiles, [ $dir, $file, $fullpath ] ); - } - else { - push( @newfiles, $dir, $file, $fullpath ); - } - } - closedir $dh; - - if ( $sort_sub ) { - return map { @{$_} } sort $sort_sub @newfiles; - } - - return @newfiles; -} - - -1; # End of File::Next -package App::Ack; - -use warnings; -use strict; - - - - -our $VERSION; -our $COPYRIGHT; -BEGIN { - $VERSION = '1.92'; - $COPYRIGHT = 'Copyright 2005-2009 Andy Lester.'; -} - -our $fh; - -BEGIN { - $fh = *STDOUT; -} - - -our %types; -our %type_wanted; -our %mappings; -our %ignore_dirs; - -our $input_from_pipe; -our $output_to_pipe; - -our $dir_sep_chars; -our $is_cygwin; -our $is_windows; - -use File::Spec (); -use File::Glob ':glob'; -use Getopt::Long (); - -BEGIN { - %ignore_dirs = ( - '.bzr' => 'Bazaar', - '.cdv' => 'Codeville', - '~.dep' => 'Interface Builder', - '~.dot' => 'Interface Builder', - '~.nib' => 'Interface Builder', - '~.plst' => 'Interface Builder', - '.git' => 'Git', - '.hg' => 'Mercurial', - '.pc' => 'quilt', - '.svn' => 'Subversion', - blib => 'Perl module building', - CVS => 'CVS', - RCS => 'RCS', - SCCS => 'SCCS', - _darcs => 'darcs', - _sgbak => 'Vault/Fortress', - 'autom4te.cache' => 'autoconf', - 'cover_db' => 'Devel::Cover', - _build => 'Module::Build', - ); - - %mappings = ( - actionscript => [qw( as mxml )], - ada => [qw( ada adb ads )], - asm => [qw( asm s )], - batch => [qw( bat cmd )], - binary => q{Binary files, as defined by Perl's -B op (default: off)}, - cc => [qw( c h xs )], - cfmx => [qw( cfc cfm cfml )], - cpp => [qw( cpp cc cxx m hpp hh h hxx )], - csharp => [qw( cs )], - css => [qw( css )], - elisp => [qw( el )], - erlang => [qw( erl hrl )], - fortran => [qw( f f77 f90 f95 f03 for ftn fpp )], - haskell => [qw( hs lhs )], - hh => [qw( h )], - html => [qw( htm html shtml xhtml )], - java => [qw( java properties )], - js => [qw( js )], - jsp => [qw( jsp jspx jhtm jhtml )], - lisp => [qw( lisp lsp )], - lua => [qw( lua )], - make => q{Makefiles}, - mason => [qw( mas mhtml mpl mtxt )], - objc => [qw( m h )], - objcpp => [qw( mm h )], - ocaml => [qw( ml mli )], - parrot => [qw( pir pasm pmc ops pod pg tg )], - perl => [qw( pl pm pod t )], - php => [qw( php phpt php3 php4 php5 phtml)], - plone => [qw( pt cpt metadata cpy py )], - python => [qw( py )], - rake => q{Rakefiles}, - ruby => [qw( rb rhtml rjs rxml erb rake )], - scala => [qw( scala )], - scheme => [qw( scm ss )], - shell => [qw( sh bash csh tcsh ksh zsh )], - skipped => q{Files, but not directories, normally skipped by ack (default: off)}, - smalltalk => [qw( st )], - sql => [qw( sql ctl )], - tcl => [qw( tcl itcl itk )], - tex => [qw( tex cls sty )], - text => q{Text files, as defined by Perl's -T op (default: off)}, - tt => [qw( tt tt2 ttml )], - vb => [qw( bas cls frm ctl vb resx )], - vim => [qw( vim )], - yaml => [qw( yaml yml )], - xml => [qw( xml dtd xslt ent )], - ); - - while ( my ($type,$exts) = each %mappings ) { - if ( ref $exts ) { - for my $ext ( @{$exts} ) { - push( @{$types{$ext}}, $type ); - } - } - } - - # These have to be checked before any filehandle diddling. - $output_to_pipe = not -t *STDOUT; - $input_from_pipe = -p STDIN; - - $is_cygwin = ($^O eq 'cygwin'); - $is_windows = ($^O =~ /MSWin32/); - $dir_sep_chars = $is_windows ? quotemeta( '\\/' ) : quotemeta( File::Spec->catfile( '', '' ) ); -} - - -sub read_ackrc { - my @files = ( $ENV{ACKRC} ); - my @dirs = - $is_windows - ? ( $ENV{HOME}, $ENV{USERPROFILE} ) - : ( '~', $ENV{HOME} ); - for my $dir ( grep { defined } @dirs ) { - for my $file ( '.ackrc', '_ackrc' ) { - push( @files, bsd_glob( "$dir/$file", GLOB_TILDE ) ); - } - } - for my $filename ( @files ) { - if ( defined $filename && -e $filename ) { - open( my $fh, '<', $filename ) or App::Ack::die( "$filename: $!\n" ); - my @lines = grep { /./ && !/^\s*#/ } <$fh>; - chomp @lines; - close $fh or App::Ack::die( "$filename: $!\n" ); - - return @lines; - } - } - - return; -} - - -sub get_command_line_options { - my %opt = ( - pager => $ENV{ACK_PAGER_COLOR} || $ENV{ACK_PAGER}, - ); - - my $getopt_specs = { - 1 => sub { $opt{1} = $opt{m} = 1 }, - 'A|after-context=i' => \$opt{after_context}, - 'B|before-context=i' => \$opt{before_context}, - 'C|context:i' => sub { shift; my $val = shift; $opt{before_context} = $opt{after_context} = ($val || 2) }, - 'a|all-types' => \$opt{all}, - 'break!' => \$opt{break}, - c => \$opt{count}, - 'color|colour!' => \$opt{color}, - 'color-match=s' => \$ENV{ACK_COLOR_MATCH}, - 'color-filename=s' => \$ENV{ACK_COLOR_FILENAME}, - 'column!' => \$opt{column}, - count => \$opt{count}, - 'env!' => sub { }, # ignore this option, it is handled beforehand - f => \$opt{f}, - flush => \$opt{flush}, - 'follow!' => \$opt{follow}, - 'g=s' => sub { shift; $opt{G} = shift; $opt{f} = 1 }, - 'G=s' => \$opt{G}, - 'group!' => sub { shift; $opt{heading} = $opt{break} = shift }, - 'heading!' => \$opt{heading}, - 'h|no-filename' => \$opt{h}, - 'H|with-filename' => \$opt{H}, - 'i|ignore-case' => \$opt{i}, - 'lines=s' => sub { shift; my $val = shift; push @{$opt{lines}}, $val }, - 'l|files-with-matches' => \$opt{l}, - 'L|files-without-matches' => sub { $opt{l} = $opt{v} = 1 }, - 'm|max-count=i' => \$opt{m}, - 'match=s' => \$opt{regex}, - 'n|no-recurse' => \$opt{n}, - o => sub { $opt{output} = '$&' }, - 'output=s' => \$opt{output}, - 'pager=s' => \$opt{pager}, - 'nopager' => sub { $opt{pager} = undef }, - 'passthru' => \$opt{passthru}, - 'print0' => \$opt{print0}, - 'Q|literal' => \$opt{Q}, - 'r|R|recurse' => sub {}, - 'smart-case!' => \$opt{smart_case}, - 'sort-files' => \$opt{sort_files}, - 'u|unrestricted' => \$opt{u}, - 'v|invert-match' => \$opt{v}, - 'w|word-regexp' => \$opt{w}, - - 'ignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); $ignore_dirs{$dir} = '--ignore-dirs' }, - 'noignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); delete $ignore_dirs{$dir} }, - - 'version' => sub { print_version_statement(); exit 1; }, - 'help|?:s' => sub { shift; show_help(@_); exit; }, - 'help-types'=> sub { show_help_types(); exit; }, - 'man' => sub { require Pod::Usage; Pod::Usage::pod2usage({-verbose => 2}); exit; }, - - 'type=s' => sub { - # Whatever --type=xxx they specify, set it manually in the hash - my $dummy = shift; - my $type = shift; - my $wanted = ($type =~ s/^no//) ? 0 : 1; # must not be undef later - - if ( exists $type_wanted{ $type } ) { - $type_wanted{ $type } = $wanted; - } - else { - App::Ack::die( qq{Unknown --type "$type"} ); - } - }, # type sub - }; - - # Stick any default switches at the beginning, so they can be overridden - # by the command line switches. - unshift @ARGV, split( ' ', $ENV{ACK_OPTIONS} ) if defined $ENV{ACK_OPTIONS}; - - # first pass through options, looking for type definitions - def_types_from_ARGV(); - - for my $i ( filetypes_supported() ) { - $getopt_specs->{ "$i!" } = \$type_wanted{ $i }; - } - - - my $parser = Getopt::Long::Parser->new(); - $parser->configure( 'bundling', 'no_ignore_case', ); - $parser->getoptions( %{$getopt_specs} ) or - App::Ack::die( 'See ack --help, ack --help-types or ack --man for options.' ); - - my $to_screen = not output_to_pipe(); - my %defaults = ( - all => 0, - color => $to_screen, - follow => 0, - break => $to_screen, - heading => $to_screen, - before_context => 0, - after_context => 0, - ); - if ( $is_windows && $defaults{color} && not $ENV{ACK_PAGER_COLOR} ) { - if ( $ENV{ACK_PAGER} || not eval { require Win32::Console::ANSI } ) { - $defaults{color} = 0; - } - } - if ( $to_screen && $ENV{ACK_PAGER_COLOR} ) { - $defaults{color} = 1; - } - - while ( my ($key,$value) = each %defaults ) { - if ( not defined $opt{$key} ) { - $opt{$key} = $value; - } - } - - if ( defined $opt{m} && $opt{m} <= 0 ) { - App::Ack::die( '-m must be greater than zero' ); - } - - for ( qw( before_context after_context ) ) { - if ( defined $opt{$_} && $opt{$_} < 0 ) { - App::Ack::die( "--$_ may not be negative" ); - } - } - - if ( defined( my $val = $opt{output} ) ) { - $opt{output} = eval qq[ sub { "$val" } ]; - } - if ( defined( my $l = $opt{lines} ) ) { - # --line=1 --line=5 is equivalent to --line=1,5 - my @lines = split( /,/, join( ',', @{$l} ) ); - - # --line=1-3 is equivalent to --line=1,2,3 - @lines = map { - my @ret; - if ( /-/ ) { - my ($from, $to) = split /-/, $_; - if ( $from > $to ) { - App::Ack::warn( "ignoring --line=$from-$to" ); - @ret = (); - } - else { - @ret = ( $from .. $to ); - } - } - else { - @ret = ( $_ ); - }; - @ret - } @lines; - - if ( @lines ) { - my %uniq; - @uniq{ @lines } = (); - $opt{lines} = [ sort { $a <=> $b } keys %uniq ]; # numerical sort and each line occurs only once! - } - else { - # happens if there are only ignored --line directives - App::Ack::die( 'All --line options are invalid.' ); - } - } - - return \%opt; -} - - -sub def_types_from_ARGV { - my @typedef; - - my $parser = Getopt::Long::Parser->new(); - # pass_through => leave unrecognized command line arguments alone - # no_auto_abbrev => otherwise -c is expanded and not left alone - $parser->configure( 'no_ignore_case', 'pass_through', 'no_auto_abbrev' ); - $parser->getoptions( - 'type-set=s' => sub { shift; push @typedef, ['c', shift] }, - 'type-add=s' => sub { shift; push @typedef, ['a', shift] }, - ) or App::Ack::die( 'See ack --help or ack --man for options.' ); - - for my $td (@typedef) { - my ($type, $ext) = split /=/, $td->[1]; - - if ( $td->[0] eq 'c' ) { - # type-set - if ( exists $mappings{$type} ) { - # can't redefine types 'make', 'skipped', 'text' and 'binary' - App::Ack::die( qq{--type-set: Builtin type "$type" cannot be changed.} ) - if ref $mappings{$type} ne 'ARRAY'; - - delete_type($type); - } - } - else { - # type-add - - # can't append to types 'make', 'skipped', 'text' and 'binary' - App::Ack::die( qq{--type-add: Builtin type "$type" cannot be changed.} ) - if exists $mappings{$type} && ref $mappings{$type} ne 'ARRAY'; - - App::Ack::warn( qq{--type-add: Type "$type" does not exist, creating with "$ext" ...} ) - unless exists $mappings{$type}; - } - - my @exts = split /,/, $ext; - s/^\.// for @exts; - - if ( !exists $mappings{$type} || ref($mappings{$type}) eq 'ARRAY' ) { - push @{$mappings{$type}}, @exts; - for my $e ( @exts ) { - push @{$types{$e}}, $type; - } - } - else { - App::Ack::die( qq{Cannot append to type "$type".} ); - } - } - - return; -} - - -sub delete_type { - my $type = shift; - - App::Ack::die( qq{Internal error: Cannot delete builtin type "$type".} ) - unless ref $mappings{$type} eq 'ARRAY'; - - delete $mappings{$type}; - delete $type_wanted{$type}; - for my $ext ( keys %types ) { - $types{$ext} = [ grep { $_ ne $type } @{$types{$ext}} ]; - } -} - - -sub ignoredir_filter { - return !exists $ignore_dirs{$_}; -} - - -sub remove_dir_sep { - my $path = shift; - $path =~ s/[$dir_sep_chars]$//; - - return $path; -} - - -use constant TEXT => 'text'; - -sub filetypes { - my $filename = shift; - - my $basename = $filename; - $basename =~ s{.*[$dir_sep_chars]}{}; - - return 'skipped' unless is_searchable( $basename ); - - my $lc_basename = lc $basename; - return ('make',TEXT) if $lc_basename eq 'makefile'; - return ('rake','ruby',TEXT) if $lc_basename eq 'rakefile'; - - # If there's an extension, look it up - if ( $filename =~ m{\.([^\.$dir_sep_chars]+)$}o ) { - my $ref = $types{lc $1}; - return (@{$ref},TEXT) if $ref; - } - - # At this point, we can't tell from just the name. Now we have to - # open it and look inside. - - return unless -e $filename; - # From Elliot Shank: - # I can't see any reason that -r would fail on these-- the ACLs look - # fine, and no program has any of them open, so the busted Windows - # file locking model isn't getting in there. If I comment the if - # statement out, everything works fine - # So, for cygwin, don't bother trying to check for readability. - if ( !$is_cygwin ) { - if ( !-r $filename ) { - App::Ack::warn( "$filename: Permission denied" ); - return; - } - } - - return 'binary' if -B $filename; - - # If there's no extension, or we don't recognize it, check the shebang line - my $fh; - if ( !open( $fh, '<', $filename ) ) { - App::Ack::warn( "$filename: $!" ); - return; - } - my $header = <$fh>; - close $fh; - - if ( $header =~ /^#!/ ) { - return ($1,TEXT) if $header =~ /\b(ruby|p(?:erl|hp|ython))\b/; - return ('shell',TEXT) if $header =~ /\b(?:ba|t?c|k|z)?sh\b/; - } - else { - return ('xml',TEXT) if $header =~ /\Q<?xml /i; - } - - return (TEXT); -} - - -sub is_searchable { - my $filename = shift; - - # If these are updated, update the --help message - return if $filename =~ /[.]bak$/; - return if $filename =~ /~$/; - return if $filename =~ m{^#.*#$}o; - return if $filename =~ m{^core\.\d+$}o; - return if $filename =~ m{[._].*\.swp$}o; - - return 1; -} - - -sub build_regex { - my $str = shift; - my $opt = shift; - - $str = quotemeta( $str ) if $opt->{Q}; - if ( $opt->{w} ) { - $str = "\\b$str" if $str =~ /^\w/; - $str = "$str\\b" if $str =~ /\w$/; - } - - my $regex_is_lc = $str eq lc $str; - if ( $opt->{i} || ($opt->{smart_case} && $regex_is_lc) ) { - $str = "(?i)$str"; - } - - return $str; -} - - -sub check_regex { - my $regex = shift; - - return unless defined $regex; - - eval { qr/$regex/ }; - if ($@) { - (my $error = $@) =~ s/ at \S+ line \d+.*//; - chomp($error); - App::Ack::die( "Invalid regex '$regex':\n $error" ); - } - - return; -} - - - - -sub warn { - return CORE::warn( _my_program(), ': ', @_, "\n" ); -} - - -sub die { - return CORE::die( _my_program(), ': ', @_, "\n" ); -} - -sub _my_program { - require File::Basename; - return File::Basename::basename( $0 ); -} - - - -sub filetypes_supported { - return keys %mappings; -} - -sub _get_thpppt { - my $y = q{_ /|,\\'!.x',=(www)=, U }; - $y =~ tr/,x!w/\nOo_/; - return $y; -} - -sub _thpppt { - my $y = _get_thpppt(); - App::Ack::print( "$y ack $_[0]!\n" ); - exit 0; -} - -sub _key { - my $str = lc shift; - $str =~ s/[^a-z]//g; - - return $str; -} - - -sub show_help { - my $help_arg = shift || 0; - - return show_help_types() if $help_arg =~ /^types?/; - - my $ignore_dirs = _listify( sort { _key($a) cmp _key($b) } keys %ignore_dirs ); - - App::Ack::print( <<"END_OF_HELP" ); -Usage: ack [OPTION]... PATTERN [FILE] - -Search for PATTERN in each source file in the tree from cwd on down. -If [FILES] is specified, then only those files/directories are checked. -ack may also search STDIN, but only if no FILE are specified, or if -one of FILES is "-". - -Default switches may be specified in ACK_OPTIONS environment variable or -an .ackrc file. If you want no dependency on the environment, turn it -off with --noenv. - -Example: ack -i select - -Searching: - -i, --ignore-case Ignore case distinctions in PATTERN - --[no]smart-case Ignore case distinctions in PATTERN, - only if PATTERN contains no upper case - Ignored if -i is specified - -v, --invert-match Invert match: select non-matching lines - -w, --word-regexp Force PATTERN to match only whole words - -Q, --literal Quote all metacharacters; PATTERN is literal - -Search output: - --line=NUM Only print line(s) NUM of each file - -l, --files-with-matches - Only print filenames containing matches - -L, --files-without-matches - Only print filenames with no matches - -o Show only the part of a line matching PATTERN - (turns off text highlighting) - --passthru Print all lines, whether matching or not - --output=expr Output the evaluation of expr for each line - (turns off text highlighting) - --match PATTERN Specify PATTERN explicitly. - -m, --max-count=NUM Stop searching in each file after NUM matches - -1 Stop searching after one match of any kind - -H, --with-filename Print the filename for each match - -h, --no-filename Suppress the prefixing filename on output - -c, --count Show number of lines matching per file - --column Show the column number of the first match - - -A NUM, --after-context=NUM - Print NUM lines of trailing context after matching - lines. - -B NUM, --before-context=NUM - Print NUM lines of leading context before matching - lines. - -C [NUM], --context[=NUM] - Print NUM lines (default 2) of output context. - - --print0 Print null byte as separator between filenames, - only works with -f, -g, -l, -L or -c. - -File presentation: - --pager=COMMAND Pipes all ack output through COMMAND. For example, - --pager="less -R". Ignored if output is redirected. - --nopager Do not send output through a pager. Cancels any - setting in ~/.ackrc, ACK_PAGER or ACK_PAGER_COLOR. - --[no]heading Print a filename heading above each file's results. - (default: on when used interactively) - --[no]break Print a break between results from different files. - (default: on when used interactively) - --group Same as --heading --break - --nogroup Same as --noheading --nobreak - --[no]color Highlight the matching text (default: on unless - output is redirected, or on Windows) - --[no]colour Same as --[no]color - --color-filename=COLOR - --color-match=COLOR Set the color for matches and filenames. - --flush Flush output immediately, even when ack is used - non-interactively (when output goes to a pipe or - file). - -File finding: - -f Only print the files found, without searching. - The PATTERN must not be specified. - -g REGEX Same as -f, but only print files matching REGEX. - --sort-files Sort the found files lexically. - -File inclusion/exclusion: - -a, --all-types All file types searched; - Ignores CVS, .svn and other ignored directories - -u, --unrestricted All files and directories searched - --[no]ignore-dir=name Add/Remove directory from the list of ignored dirs - -r, -R, --recurse Recurse into subdirectories (ack's default behavior) - -n, --no-recurse No descending into subdirectories - -G REGEX Only search files that match REGEX - - --perl Include only Perl files. - --type=perl Include only Perl files. - --noperl Exclude Perl files. - --type=noperl Exclude Perl files. - See "ack --help type" for supported filetypes. - - --type-set TYPE=.EXTENSION[,.EXT2[,...]] - Files with the given EXTENSION(s) are recognized as - being of type TYPE. This replaces an existing - definition for type TYPE. - --type-add TYPE=.EXTENSION[,.EXT2[,...]] - Files with the given EXTENSION(s) are recognized as - being of (the existing) type TYPE - - --[no]follow Follow symlinks. Default is off. - - Directories ignored by default: - $ignore_dirs - - Files not checked for type: - /~\$/ - Unix backup files - /#.+#\$/ - Emacs swap files - /[._].*\\.swp\$/ - Vi(m) swap files - /core\\.\\d+\$/ - core dumps - -Miscellaneous: - --noenv Ignore environment variables and ~/.ackrc - --help This help - --man Man page - --version Display version & copyright - --thpppt Bill the Cat - -Exit status is 0 if match, 1 if no match. - -This is version $VERSION of ack. -END_OF_HELP - - return; - } - - - -sub show_help_types { - App::Ack::print( <<'END_OF_HELP' ); -Usage: ack [OPTION]... PATTERN [FILES] - -The following is the list of filetypes supported by ack. You can -specify a file type with the --type=TYPE format, or the --TYPE -format. For example, both --type=perl and --perl work. - -Note that some extensions may appear in multiple types. For example, -.pod files are both Perl and Parrot. - -END_OF_HELP - - my @types = filetypes_supported(); - my $maxlen = 0; - for ( @types ) { - $maxlen = length if $maxlen < length; - } - for my $type ( sort @types ) { - next if $type =~ /^-/; # Stuff to not show - my $ext_list = $mappings{$type}; - - if ( ref $ext_list ) { - $ext_list = join( ' ', map { ".$_" } @{$ext_list} ); - } - App::Ack::print( sprintf( " --[no]%-*.*s %s\n", $maxlen, $maxlen, $type, $ext_list ) ); - } - - return; -} - -sub _listify { - my @whats = @_; - - return '' if !@whats; - - my $end = pop @whats; - my $str = @whats ? join( ', ', @whats ) . " and $end" : $end; - - no warnings 'once'; - require Text::Wrap; - $Text::Wrap::columns = 75; - return Text::Wrap::wrap( '', ' ', $str ); -} - - -sub get_version_statement { - require Config; - - my $copyright = get_copyright(); - my $this_perl = $Config::Config{perlpath}; - if ($^O ne 'VMS') { - my $ext = $Config::Config{_exe}; - $this_perl .= $ext unless $this_perl =~ m/$ext$/i; - } - my $ver = sprintf( '%vd', $^V ); - - return <<"END_OF_VERSION"; -ack $VERSION -Running under Perl $ver at $this_perl - -$copyright - -This program is free software; you can redistribute it and/or modify -it under the terms of either: the GNU General Public License as -published by the Free Software Foundation; or the Artistic License. -END_OF_VERSION -} - - -sub print_version_statement { - App::Ack::print( get_version_statement() ); - - return; -} - - -sub get_copyright { - return $COPYRIGHT; -} - - -sub load_colors { - eval 'use Term::ANSIColor ()'; - - $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow'; - $ENV{ACK_COLOR_FILENAME} ||= 'bold green'; - - return; -} - - -sub is_interesting { - return if /^\./; - - my $include; - - for my $type ( filetypes( $File::Next::name ) ) { - if ( defined $type_wanted{$type} ) { - if ( $type_wanted{$type} ) { - $include = 1; - } - else { - return; - } - } - } - - return $include; -} - - - -# print subs added in order to make it easy for a third party -# module (such as App::Wack) to redefine the display methods -# and show the results in a different way. -sub print { print {$fh} @_ } -sub print_first_filename { App::Ack::print( $_[0], "\n" ) } -sub print_blank_line { App::Ack::print( "\n" ) } -sub print_separator { App::Ack::print( "--\n" ) } -sub print_filename { App::Ack::print( $_[0], $_[1] ) } -sub print_line_no { App::Ack::print( $_[0], $_[1] ) } -sub print_column_no { App::Ack::print( $_[0], $_[1] ) } -sub print_count { - my $filename = shift; - my $nmatches = shift; - my $ors = shift; - my $count = shift; - - App::Ack::print( $filename ); - App::Ack::print( ':', $nmatches ) if $count; - App::Ack::print( $ors ); -} - -sub print_count0 { - my $filename = shift; - my $ors = shift; - - App::Ack::print( $filename, ':0', $ors ); -} - - - -{ - my $filename; - my $regex; - my $display_filename; - - my $keep_context; - - my $last_output_line; # number of the last line that has been output - my $any_output; # has there been any output for the current file yet - my $context_overall_output_count; # has there been any output at all - -sub search_resource { - my $res = shift; - my $opt = shift; - - $filename = $res->name(); - - my $v = $opt->{v}; - my $passthru = $opt->{passthru}; - my $max = $opt->{m}; - my $nmatches = 0; - - $display_filename = undef; - - # for --line processing - my $has_lines = 0; - my @lines; - if ( defined $opt->{lines} ) { - $has_lines = 1; - @lines = ( @{$opt->{lines}}, -1 ); - undef $regex; # Don't match when printing matching line - } - else { - $regex = qr/$opt->{regex}/; - } - - # for context processing - $last_output_line = -1; - $any_output = 0; - my $before_context = $opt->{before_context}; - my $after_context = $opt->{after_context}; - - $keep_context = ($before_context || $after_context) && !$passthru; - - my @before; - my $before_starts_at_line; - my $after = 0; # number of lines still to print after a match - - while ( $res->next_text ) { - # XXX Optimize away the case when there are no more @lines to find. - # XXX $has_lines, $passthru and $v never change. Optimize. - if ( $has_lines - ? $. != $lines[0] # $lines[0] should be a scalar - : $v ? m/$regex/ : !m/$regex/ ) { - if ( $passthru ) { - App::Ack::print( $_ ); - next; - } - - if ( $keep_context ) { - if ( $after ) { - print_match_or_context( $opt, 0, $., $-[0], $+[0], $_ ); - $after--; - } - elsif ( $before_context ) { - if ( @before ) { - if ( @before >= $before_context ) { - shift @before; - ++$before_starts_at_line; - } - } - else { - $before_starts_at_line = $.; - } - push @before, $_; - } - last if $max && ( $nmatches >= $max ) && !$after; - } - next; - } # not a match - - ++$nmatches; - - # print an empty line as a divider before first line in each file (not before the first file) - if ( !$any_output && $opt->{show_filename} && $opt->{break} && defined( $context_overall_output_count ) ) { - App::Ack::print_blank_line(); - } - - shift @lines if $has_lines; - - if ( $res->is_binary ) { - App::Ack::print( "Binary file $filename matches\n" ); - last; - } - if ( $keep_context ) { - if ( @before ) { - print_match_or_context( $opt, 0, $before_starts_at_line, $-[0], $+[0], @before ); - @before = (); - $before_starts_at_line = 0; - } - if ( $max && $nmatches > $max ) { - --$after; - } - else { - $after = $after_context; - } - } - print_match_or_context( $opt, 1, $., $-[0], $+[0], $_ ); - - last if $max && ( $nmatches >= $max ) && !$after; - } # while - - return $nmatches; -} # search_resource() - - - -sub print_match_or_context { - my $opt = shift; # opts array - my $is_match = shift; # is there a match on the line? - my $line_no = shift; - my $match_start = shift; - my $match_end = shift; - - my $color = $opt->{color}; - my $heading = $opt->{heading}; - my $show_filename = $opt->{show_filename}; - my $show_column = $opt->{column}; - - if ( $show_filename ) { - if ( not defined $display_filename ) { - $display_filename = - $color - ? Term::ANSIColor::colored( $filename, $ENV{ACK_COLOR_FILENAME} ) - : $filename; - if ( $heading && !$any_output ) { - App::Ack::print_first_filename($display_filename); - } - } - } - - my $sep = $is_match ? ':' : '-'; - my $output_func = $opt->{output}; - for ( @_ ) { - if ( $keep_context && !$output_func ) { - if ( ( $last_output_line != $line_no - 1 ) && - ( $any_output || ( !$heading && defined( $context_overall_output_count ) ) ) ) { - App::Ack::print_separator(); - } - # to ensure separators between different files when --noheading - - $last_output_line = $line_no; - } - - if ( $show_filename ) { - App::Ack::print_filename($display_filename, $sep) if not $heading; - App::Ack::print_line_no($line_no, $sep); - } - - if ( $output_func ) { - while ( /$regex/go ) { - App::Ack::print( $output_func->() . "\n" ); - } - } - else { - if ( $color && $is_match && $regex && - s/$regex/Term::ANSIColor::colored( substr($_, $-[0], $+[0] - $-[0]), $ENV{ACK_COLOR_MATCH} )/eg ) { - # At the end of the line reset the color and remove newline - s/[\r\n]*\z/\e[0m\e[K/; - } - else { - # remove any kind of newline at the end of the line - s/[\r\n]*\z//; - } - if ( $show_column ) { - App::Ack::print_column_no( $match_start+1, $sep ); - } - App::Ack::print($_ . "\n"); - } - $any_output = 1; - ++$context_overall_output_count; - ++$line_no; - } - - return; -} # print_match_or_context() - -} # scope around search_resource() and print_match_or_context() - - - -sub search_and_list { - my $res = shift; - my $opt = shift; - - my $nmatches = 0; - my $count = $opt->{count}; - my $ors = $opt->{print0} ? "\0" : "\n"; # output record separator - - my $regex = qr/$opt->{regex}/; - - if ( $opt->{v} ) { - while ( $res->next_text ) { - if ( /$regex/ ) { - return 0 unless $count; - } - else { - ++$nmatches; - } - } - } - else { - while ( $res->next_text ) { - if ( /$regex/ ) { - ++$nmatches; - last unless $count; - } - } - } - - if ( $nmatches ) { - App::Ack::print_count( $res->name, $nmatches, $ors, $count ); - } - elsif ( $count && !$opt->{l} ) { - App::Ack::print_count0( $res->name, $ors ); - } - - return $nmatches ? 1 : 0; -} # search_and_list() - - - -sub filetypes_supported_set { - return grep { defined $type_wanted{$_} && ($type_wanted{$_} == 1) } filetypes_supported(); -} - - - -sub print_files { - my $iter = shift; - my $opt = shift; - - my $ors = $opt->{print0} ? "\0" : "\n"; - - my $nmatches = 0; - while ( defined ( my $file = $iter->() ) ) { - App::Ack::print $file, $ors; - $nmatches++; - last if $opt->{1}; - } - - return $nmatches; -} - - -sub print_files_with_matches { - my $iter = shift; - my $opt = shift; - - my $nmatches = 0; - while ( defined ( my $filename = $iter->() ) ) { - my $repo = App::Ack::Repository::Basic->new( $filename ); - my $res; - while ( $res = $repo->next_resource() ) { - $nmatches += search_and_list( $res, $opt ); - $res->close(); - last if $nmatches && $opt->{1}; - } - $repo->close(); - } - - return $nmatches; -} - - -sub print_matches { - my $iter = shift; - my $opt = shift; - - $opt->{show_filename} = 0 if $opt->{h}; - $opt->{show_filename} = 1 if $opt->{H}; - - my $nmatches = 0; - while ( defined ( my $filename = $iter->() ) ) { - my $repo; - my $tarballs_work = 0; - if ( $tarballs_work && $filename =~ /\.tar\.gz$/ ) { - App::Ack::die( 'Not working here yet' ); - require App::Ack::Repository::Tar; # XXX Error checking - $repo = App::Ack::Repository::Tar->new( $filename ); - } - else { - $repo = App::Ack::Repository::Basic->new( $filename ); - } - $repo or next; - - while ( my $res = $repo->next_resource() ) { - my $needs_line_scan; - if ( $opt->{regex} && !$opt->{passthru} ) { - $needs_line_scan = $res->needs_line_scan( $opt ); - if ( $needs_line_scan ) { - $res->reset(); - } - } - else { - $needs_line_scan = 1; - } - if ( $needs_line_scan ) { - $nmatches += search_resource( $res, $opt ); - } - $res->close(); - } - last if $nmatches && $opt->{1}; - $repo->close(); - } - return $nmatches; -} - - -sub filetype_setup { - my $filetypes_supported_set = filetypes_supported_set(); - # If anyone says --no-whatever, we assume all other types must be on. - if ( !$filetypes_supported_set ) { - for my $i ( keys %type_wanted ) { - $type_wanted{$i} = 1 unless ( defined( $type_wanted{$i} ) || $i eq 'binary' || $i eq 'text' || $i eq 'skipped' ); - } - } - return; -} - - -EXPAND_FILENAMES_SCOPE: { - my $filter; - - sub expand_filenames { - my $argv = shift; - - my $attr; - my @files; - - foreach my $pattern ( @{$argv} ) { - my @results = bsd_glob( $pattern ); - - if (@results == 0) { - @results = $pattern; # Glob didn't match, pass it thru unchanged - } - elsif ( (@results > 1) or ($results[0] ne $pattern) ) { - if (not defined $filter) { - eval 'require Win32::File;'; - if ($@) { - $filter = 0; - } - else { - $filter = Win32::File::HIDDEN()|Win32::File::SYSTEM(); - } - } # end unless we've tried to load Win32::File - if ( $filter ) { - # Filter out hidden and system files: - @results = grep { not(Win32::File::GetAttributes($_, $attr) and $attr & $filter) } @results; - App::Ack::warn( "$pattern: Matched only hidden files" ) unless @results; - } # end if we can filter by file attributes - } # end elsif this pattern got expanded - - push @files, @results; - } # end foreach pattern - - return \@files; - } # end expand_filenames -} # EXPAND_FILENAMES_SCOPE - - - -sub get_starting_points { - my $argv = shift; - my $opt = shift; - - my @what; - - if ( @{$argv} ) { - @what = @{ $is_windows ? expand_filenames($argv) : $argv }; - $_ = File::Next::reslash( $_ ) for @what; - - # Show filenames unless we've specified one single file - $opt->{show_filename} = (@what > 1) || (!-f $what[0]); - } - else { - @what = '.'; # Assume current directory - $opt->{show_filename} = 1; - } - - for my $start_point (@what) { - App::Ack::warn( "$start_point: No such file or directory" ) unless -e $start_point; - } - return \@what; -} - - - -sub get_iterator { - my $what = shift; - my $opt = shift; - - # Starting points are always searched, no matter what - my %starting_point = map { ($_ => 1) } @{$what}; - - my $g_regex = defined $opt->{G} ? qr/$opt->{G}/ : undef; - my $file_filter; - - if ( $g_regex ) { - $file_filter - = $opt->{u} ? sub { $File::Next::name =~ /$g_regex/ } # XXX Maybe this should be a 1, no? - : $opt->{all} ? sub { $starting_point{ $File::Next::name } || ( $File::Next::name =~ /$g_regex/ && is_searchable( $_ ) ) } - : sub { $starting_point{ $File::Next::name } || ( $File::Next::name =~ /$g_regex/ && is_interesting( @_ ) ) } - ; - } - else { - $file_filter - = $opt->{u} ? sub {1} - : $opt->{all} ? sub { $starting_point{ $File::Next::name } || is_searchable( $_ ) } - : sub { $starting_point{ $File::Next::name } || is_interesting( @_ ) } - ; - } - - my $descend_filter - = $opt->{n} ? sub {0} - : $opt->{u} ? sub {1} - : \&ignoredir_filter; - - my $iter = - File::Next::files( { - file_filter => $file_filter, - descend_filter => $descend_filter, - error_handler => sub { my $msg = shift; App::Ack::warn( $msg ) }, - sort_files => $opt->{sort_files}, - follow_symlinks => $opt->{follow}, - }, @{$what} ); - return $iter; -} - - -sub set_up_pager { - my $command = shift; - - return if App::Ack::output_to_pipe(); - - my $pager; - if ( not open( $pager, '|-', $command ) ) { - App::Ack::die( qq{Unable to pipe to pager "$command": $!} ); - } - $fh = $pager; - - return; -} - - -sub input_from_pipe { - return $input_from_pipe; -} - - - -sub output_to_pipe { - return $output_to_pipe; -} - - - -1; # End of App::Ack -package App::Ack::Repository; - - -use warnings; -use strict; - -sub FAIL { - require Carp; - Carp::confess( 'Must be overloaded' ); -} - - -sub new { - FAIL(); -} - - -sub next_resource { - FAIL(); -} - - -sub close { - FAIL(); -} - -1; -package App::Ack::Resource; - - -use warnings; -use strict; - -sub FAIL { - require Carp; - Carp::confess( 'Must be overloaded' ); -} - - -sub new { - FAIL(); -} - - -sub name { - FAIL(); -} - - -sub is_binary { - FAIL(); -} - - - -sub needs_line_scan { - FAIL(); -} - - -sub reset { - FAIL(); -} - - -sub next_text { - FAIL(); -} - - -sub close { - FAIL(); -} - -1; -package App::Ack::Plugin::Basic; - - - -package App::Ack::Resource::Basic; - - -use warnings; -use strict; - - -our @ISA = qw( App::Ack::Resource ); - - -sub new { - my $class = shift; - my $filename = shift; - - my $self = bless { - filename => $filename, - fh => undef, - could_be_binary => undef, - opened => undef, - id => undef, - }, $class; - - if ( $self->{filename} eq '-' ) { - $self->{fh} = *STDIN; - $self->{could_be_binary} = 0; - } - else { - if ( !open( $self->{fh}, '<', $self->{filename} ) ) { - App::Ack::warn( "$self->{filename}: $!" ); - return; - } - $self->{could_be_binary} = 1; - } - - return $self; -} - - -sub name { - my $self = shift; - - return $self->{filename}; -} - - -sub is_binary { - my $self = shift; - - if ( $self->{could_be_binary} ) { - return -B $self->{filename}; - } - - return 0; -} - - - -sub needs_line_scan { - my $self = shift; - my $opt = shift; - - return 1 if $opt->{v}; - - my $size = -s $self->{fh}; - if ( $size == 0 ) { - return 0; - } - elsif ( $size > 100_000 ) { - return 1; - } - - my $buffer; - my $rc = sysread( $self->{fh}, $buffer, $size ); - if ( not defined $rc ) { - App::Ack::warn( "$self->{filename}: $!" ); - return 1; - } - return 0 unless $rc && ( $rc == $size ); - - my $regex = $opt->{regex}; - return $buffer =~ /$regex/m; -} - - -sub reset { - my $self = shift; - - seek( $self->{fh}, 0, 0 ) - or App::Ack::warn( "$self->{filename}: $!" ); - - return; -} - - -sub next_text { - if ( defined ($_ = readline $_[0]->{fh}) ) { - $. = ++$_[0]->{line}; - return 1; - } - - return; -} - - -sub close { - my $self = shift; - - if ( not close $self->{fh} ) { - App::Ack::warn( $self->name() . ": $!" ); - } - - return; -} - -package App::Ack::Repository::Basic; - - -our @ISA = qw( App::Ack::Repository ); - - -use warnings; -use strict; - -sub new { - my $class = shift; - my $filename = shift; - - my $self = bless { - filename => $filename, - nexted => 0, - }, $class; - - return $self; -} - - -sub next_resource { - my $self = shift; - - return if $self->{nexted}; - $self->{nexted} = 1; - - return App::Ack::Resource::Basic->new( $self->{filename} ); -} - - -sub close { -} - - - -1; diff --git a/mount-fedora-image b/mount-fedora-image deleted file mode 100755 index 8413762..0000000 --- a/mount-fedora-image +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -# -# Mounts Fedora/Solr disk image, downloadable from the following URL: -# http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image - -export FEDORA_IMAGE_DIR=$HOME/Documents/Yale/fedora-testing-image -export FEDORA_IMAGE_NAME=$FEDORA_IMAGE_DIR/fedora-3.2.1-solr-1.3.0-testing.dmg -export FEDORA_HOME=/Volumes/fedora-solr-testing/fedora -export CATLINA_HOME=$FEDORA_HOME/tomcat -hdiutil attach $FEDORA_IMAGE_NAME -shadow $FEDORA_IMAGE_NAME.shadow
anarchivist/tildebin
73af506e98dffc1573481cd113dafcc10790c743
Fix git-archive-all; remove fits
diff --git a/fits b/fits deleted file mode 100755 index 1b2f323..0000000 --- a/fits +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -export FITS_DIR=/opt/fits-0.3.2 -exec $FITS_DIR/fits.sh "$@" diff --git a/git-archive-all.sh b/git-archive-all.sh index 9a2d44d..af97d96 100755 --- a/git-archive-all.sh +++ b/git-archive-all.sh @@ -1,208 +1,208 @@ #!/bin/bash - # # File: git-archive-all.sh # # Description: A utility script that builds an archive file(s) of all # git repositories and submodules in the current path. # Useful for creating a single tarfile of a git super- # project that contains other submodules. # # Examples: Use git-archive-all.sh to create archive distributions # from git repositories. To use, simply do: # # cd $GIT_DIR; git-archive-all.sh # # where $GIT_DIR is the root of your git superproject. # # License: GPL3 # ############################################################################### # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################### # DEBUGGING set -e set -C # noclobber # TRAP SIGNALS trap 'cleanup' QUIT EXIT # For security reasons, explicitly set the internal field separator # to newline, space, tab OLD_IFS=$IFS IFS=' ' function cleanup () { rm -f $TMPFILE rm -f $TOARCHIVE IFS="$OLD_IFS" } function usage () { echo "Usage is as follows:" echo echo "$PROGRAM <--version>" echo " Prints the program version number on a line by itself and exits." echo echo "$PROGRAM <--usage|--help|-?>" echo " Prints this usage output and exits." echo echo "$PROGRAM [--format <fmt>] [--prefix <path>] [--separate|-s] [output_file]" echo " Creates an archive for the entire git superproject, and its submodules" echo " using the passed parameters, described below." echo echo " If '--format' is specified, the archive is created with the named" echo " git archiver backend. Obviously, this must be a backend that git-archive" echo " understands. The format defaults to 'tar' if not specified." echo echo " If '--prefix' is specified, the archive's superproject and all submodules" echo " are created with the <path> prefix named. The default is to not use one." echo echo " If '--separate' or '-s' is specified, individual archives will be created" echo " for each of the superproject itself and its submodules. The default is to" echo " concatenate individual archives into one larger archive." echo echo " If 'output_file' is specified, the resulting archive is created as the" echo " file named. This parameter is essentially a path that must be writeable." echo " When combined with '--separate' ('-s') this path must refer to a directory." echo " Without this parameter or when combined with '--separate' the resulting" echo " archive(s) are named with a dot-separated path of the archived directory and" echo " a file extension equal to their format (e.g., 'superdir.submodule1dir.tar')." } function version () { echo "$PROGRAM version $VERSION" } # Internal variables and initializations. readonly PROGRAM=`basename "$0"` readonly VERSION=0.2 OLD_PWD="`pwd`" TMPDIR=${TMPDIR:-/tmp} TMPFILE=`mktemp "$TMPDIR/$PROGRAM.XXXXXX"` # Create a place to store our work's progress TOARCHIVE=`mktemp "$TMPDIR/$PROGRAM.toarchive.XXXXXX"` OUT_FILE=$OLD_PWD # assume "this directory" without a name change by default SEPARATE=0 FORMAT=tar PREFIX= TREEISH=HEAD # RETURN VALUES/EXIT STATUS CODES readonly E_BAD_OPTION=254 readonly E_UNKNOWN=255 # Process command-line arguments. while test $# -gt 0; do case $1 in --format ) shift FORMAT="$1" shift ;; --prefix ) shift PREFIX="$1" shift ;; --separate | -s ) shift SEPARATE=1 ;; --version ) version exit ;; -? | --usage | --help ) usage exit ;; -* ) echo "Unrecognized option: $1" >&2 usage exit $E_BAD_OPTION ;; * ) break ;; esac done if [ ! -z "$1" ]; then OUT_FILE="$1" shift fi # Validate parameters; error early, error often. if [ $SEPARATE -eq 1 -a ! -d $OUT_FILE ]; then echo "When creating multiple archives, your destination must be a directory." echo "If it's not, you risk being surprised when your files are overwritten." exit elif [ `git config -l | grep -q '^core\.bare=false'; echo $?` -ne 0 ]; then echo "$PROGRAM must be run from a git working copy (i.e., not a bare repository)." exit fi # Create the superproject's git-archive git archive --format=$FORMAT --prefix="$PREFIX" $TREEISH > $TMPDIR/$(basename $(pwd)).$FORMAT echo $TMPDIR/$(basename $(pwd)).$FORMAT >| $TMPFILE # clobber on purpose superfile=`head -n 1 $TMPFILE` # find all '.git' dirs, these show us the remaining to-be-archived dirs find . -name '.git' -type d -print | sed -e 's/^\.\///' -e 's/\.git$//' | grep -v '^$' >> $TOARCHIVE while read path; do - TREEISH=$(git-submodule | grep "^ .*${path%/} " | cut -d ' ' -f 2) # git-submodule does not list trailing slashes in $path + TREEISH=$(git submodule | grep "^ .*${path%/} " | cut -d ' ' -f 2) # git-submodule does not list trailing slashes in $path cd "$path" git archive --format=$FORMAT --prefix="${PREFIX}$path" ${TREEISH:-HEAD} > "$TMPDIR"/"$(echo "$path" | sed -e 's/\//./g')"$FORMAT if [ $FORMAT == 'zip' ]; then # delete the empty directory entry; zipped submodules won't unzip if we don't do this zip -d "$(tail -n 1 $TMPFILE)" "${PREFIX}${path%/}" >/dev/null # remove trailing '/' fi echo "$TMPDIR"/"$(echo "$path" | sed -e 's/\//./g')"$FORMAT >> $TMPFILE cd "$OLD_PWD" done < $TOARCHIVE # Concatenate archives into a super-archive. if [ $SEPARATE -eq 0 ]; then if [ $FORMAT == 'tar' ]; then sed -e '1d' $TMPFILE | while read file; do tar --concatenate -f "$superfile" "$file" && rm -f "$file" done elif [ $FORMAT == 'zip' ]; then sed -e '1d' $TMPFILE | while read file; do # zip incorrectly stores the full path, so cd and then grow cd `dirname "$file"` zip -g "$superfile" `basename "$file"` && rm -f "$file" done cd "$OLD_PWD" fi echo "$superfile" >| $TMPFILE # clobber on purpose fi while read file; do mv "$file" "$OUT_FILE" done < $TMPFILE
anarchivist/tildebin
bc546b05dcad2b1db4c745ab0f6d7b62bb9158f1
add git-archive-all.sh
diff --git a/git-archive-all.sh b/git-archive-all.sh new file mode 100755 index 0000000..9a2d44d --- /dev/null +++ b/git-archive-all.sh @@ -0,0 +1,208 @@ +#!/bin/bash - +# +# File: git-archive-all.sh +# +# Description: A utility script that builds an archive file(s) of all +# git repositories and submodules in the current path. +# Useful for creating a single tarfile of a git super- +# project that contains other submodules. +# +# Examples: Use git-archive-all.sh to create archive distributions +# from git repositories. To use, simply do: +# +# cd $GIT_DIR; git-archive-all.sh +# +# where $GIT_DIR is the root of your git superproject. +# +# License: GPL3 +# +############################################################################### +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# +############################################################################### + +# DEBUGGING +set -e +set -C # noclobber + +# TRAP SIGNALS +trap 'cleanup' QUIT EXIT + +# For security reasons, explicitly set the internal field separator +# to newline, space, tab +OLD_IFS=$IFS +IFS=' + ' + +function cleanup () { + rm -f $TMPFILE + rm -f $TOARCHIVE + IFS="$OLD_IFS" +} + +function usage () { + echo "Usage is as follows:" + echo + echo "$PROGRAM <--version>" + echo " Prints the program version number on a line by itself and exits." + echo + echo "$PROGRAM <--usage|--help|-?>" + echo " Prints this usage output and exits." + echo + echo "$PROGRAM [--format <fmt>] [--prefix <path>] [--separate|-s] [output_file]" + echo " Creates an archive for the entire git superproject, and its submodules" + echo " using the passed parameters, described below." + echo + echo " If '--format' is specified, the archive is created with the named" + echo " git archiver backend. Obviously, this must be a backend that git-archive" + echo " understands. The format defaults to 'tar' if not specified." + echo + echo " If '--prefix' is specified, the archive's superproject and all submodules" + echo " are created with the <path> prefix named. The default is to not use one." + echo + echo " If '--separate' or '-s' is specified, individual archives will be created" + echo " for each of the superproject itself and its submodules. The default is to" + echo " concatenate individual archives into one larger archive." + echo + echo " If 'output_file' is specified, the resulting archive is created as the" + echo " file named. This parameter is essentially a path that must be writeable." + echo " When combined with '--separate' ('-s') this path must refer to a directory." + echo " Without this parameter or when combined with '--separate' the resulting" + echo " archive(s) are named with a dot-separated path of the archived directory and" + echo " a file extension equal to their format (e.g., 'superdir.submodule1dir.tar')." +} + +function version () { + echo "$PROGRAM version $VERSION" +} + +# Internal variables and initializations. +readonly PROGRAM=`basename "$0"` +readonly VERSION=0.2 + +OLD_PWD="`pwd`" +TMPDIR=${TMPDIR:-/tmp} +TMPFILE=`mktemp "$TMPDIR/$PROGRAM.XXXXXX"` # Create a place to store our work's progress +TOARCHIVE=`mktemp "$TMPDIR/$PROGRAM.toarchive.XXXXXX"` +OUT_FILE=$OLD_PWD # assume "this directory" without a name change by default +SEPARATE=0 + +FORMAT=tar +PREFIX= +TREEISH=HEAD + +# RETURN VALUES/EXIT STATUS CODES +readonly E_BAD_OPTION=254 +readonly E_UNKNOWN=255 + +# Process command-line arguments. +while test $# -gt 0; do + case $1 in + --format ) + shift + FORMAT="$1" + shift + ;; + + --prefix ) + shift + PREFIX="$1" + shift + ;; + + --separate | -s ) + shift + SEPARATE=1 + ;; + + --version ) + version + exit + ;; + + -? | --usage | --help ) + usage + exit + ;; + + -* ) + echo "Unrecognized option: $1" >&2 + usage + exit $E_BAD_OPTION + ;; + + * ) + break + ;; + esac +done + +if [ ! -z "$1" ]; then + OUT_FILE="$1" + shift +fi + +# Validate parameters; error early, error often. +if [ $SEPARATE -eq 1 -a ! -d $OUT_FILE ]; then + echo "When creating multiple archives, your destination must be a directory." + echo "If it's not, you risk being surprised when your files are overwritten." + exit +elif [ `git config -l | grep -q '^core\.bare=false'; echo $?` -ne 0 ]; then + echo "$PROGRAM must be run from a git working copy (i.e., not a bare repository)." + exit +fi + +# Create the superproject's git-archive +git archive --format=$FORMAT --prefix="$PREFIX" $TREEISH > $TMPDIR/$(basename $(pwd)).$FORMAT +echo $TMPDIR/$(basename $(pwd)).$FORMAT >| $TMPFILE # clobber on purpose +superfile=`head -n 1 $TMPFILE` + +# find all '.git' dirs, these show us the remaining to-be-archived dirs +find . -name '.git' -type d -print | sed -e 's/^\.\///' -e 's/\.git$//' | grep -v '^$' >> $TOARCHIVE + +while read path; do + TREEISH=$(git-submodule | grep "^ .*${path%/} " | cut -d ' ' -f 2) # git-submodule does not list trailing slashes in $path + cd "$path" + git archive --format=$FORMAT --prefix="${PREFIX}$path" ${TREEISH:-HEAD} > "$TMPDIR"/"$(echo "$path" | sed -e 's/\//./g')"$FORMAT + if [ $FORMAT == 'zip' ]; then + # delete the empty directory entry; zipped submodules won't unzip if we don't do this + zip -d "$(tail -n 1 $TMPFILE)" "${PREFIX}${path%/}" >/dev/null # remove trailing '/' + fi + echo "$TMPDIR"/"$(echo "$path" | sed -e 's/\//./g')"$FORMAT >> $TMPFILE + cd "$OLD_PWD" +done < $TOARCHIVE + +# Concatenate archives into a super-archive. +if [ $SEPARATE -eq 0 ]; then + if [ $FORMAT == 'tar' ]; then + sed -e '1d' $TMPFILE | while read file; do + tar --concatenate -f "$superfile" "$file" && rm -f "$file" + done + elif [ $FORMAT == 'zip' ]; then + sed -e '1d' $TMPFILE | while read file; do + # zip incorrectly stores the full path, so cd and then grow + cd `dirname "$file"` + zip -g "$superfile" `basename "$file"` && rm -f "$file" + done + cd "$OLD_PWD" + fi + + echo "$superfile" >| $TMPFILE # clobber on purpose +fi + +while read file; do + mv "$file" "$OUT_FILE" +done < $TMPFILE diff --git a/svn-authorsfile b/svn-authorsfile index 5d1a618..482ffa7 100755 --- a/svn-authorsfile +++ b/svn-authorsfile @@ -1,6 +1,6 @@ -#!/usr/bin/bash +#!/bin/bash authors=$(svn log -q | grep -e '^r' | awk 'BEGIN { FS = "|" } ; { print $2 }' | sort | uniq) for author in ${authors}; do echo "${author} = NAME <USER@DOMAIN>"; done
anarchivist/tildebin
fcadf5a280b51b3ed887ae864e19a206f7186956
adding marcstats
diff --git a/README.textile b/README.textile index 3db0d92..070659d 100644 --- a/README.textile +++ b/README.textile @@ -1,14 +1,15 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. * Blame "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist h2. Possibly incomplete list of scripts and what they do * ack: Standalone version of "ack, the grep replacement":http://github.com/petdance/ack * fits: Launch "FITS, the file information toolset":http://code.google.com/p/fits/ +* marcstats: get statistics on files containing MARC records (from "this gist":http://gist.github.com/262826 ) * mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image * osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. * svn-authorsfile: generate a skeletal git-svn authorsfile from an svn commit log * yale-apartments-feed: generate an RSS feed from Yale's off-campus housing ads \ No newline at end of file diff --git a/marcstats b/marcstats new file mode 100755 index 0000000..01f0f5b --- /dev/null +++ b/marcstats @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +# http://gist.github.com/262826 +# originally by edsu - original at http://inkdroid.org/bzr/bin/marc-tags + +import pymarc +import sys + +stats = {} + +def tally(r): + for f in r.fields: + stats[f.tag] = stats.get(f.tag, 0) + 1 + +records = 0 +for filename in sys.argv[1:]: + for r in pymarc.MARCReader(file(filename)): + records += 1 + tally(r) + +#pymarc.map_xml(get_stats, *sys.argv[1:]) + +for e in stats: + print "%s : %s" % (e, stats[e]) + +print "%s total records" % records \ No newline at end of file
anarchivist/tildebin
7a8447d8286c1ac2aea584ba9646a3d3915d54cb
Adding yale-apartments-feed
diff --git a/README.textile b/README.textile index 401d7db..1f360d6 100644 --- a/README.textile +++ b/README.textile @@ -1,13 +1,14 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. * Blame "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist h2. Possibly incomplete list of scripts and what they do * ack: Standalone version of "ack, the grep replacemetn":http://github.com/petdance/ack * fits: Launch "FITS, the file information toolset":http://code.google.com/p/fits/ * mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image * osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. -* svn-authorsfile: generate a skeletal git-svn authorsfile from an svn commit log \ No newline at end of file +* svn-authorsfile: generate a skeletal git-svn authorsfile from an svn commit log +* yale-apartments-feed: generate an RSS feed from Yale's off-campus housing ads \ No newline at end of file
anarchivist/tildebin
a33d760e159ac079fabf79ceb6cd3b6b4d9ee0c8
Adding yale-apartments-feed
diff --git a/yale-apartments-feed b/yale-apartments-feed new file mode 100755 index 0000000..aa798d4 --- /dev/null +++ b/yale-apartments-feed @@ -0,0 +1,64 @@ +#!/usr/bin/env python + +# Scrape listings from Yale's off-campus housing ads & generate feeds + +import sys +import time +import urllib2 + +from BeautifulSoup import BeautifulSoup +from feedformatter import Feed + +BASE_URL = 'http://www-iisp1.its.yale.edu/offcampus/' +SOURCE_URL = BASE_URL + 'offcampus_housing_results.asp' +BASE_DATA = 'rb_Orderby=DateListed&cmd_Search=Search' + +def parse_field(field): + if field.find('a') is not None: + url = field.find('a')['href'] + return BASE_URL + url.split('&')[0] + else: + return field.string + +def row_to_dict(row): + item = {} + item['title'] = row[0] + ', ' + row[1] + ' ($' + row[5] + ')' + item['link'] = row[9] + item['guid'] = row[9] + item['description'] = '''<ul> + <li><strong>%s Term, %s Room %s</strong></li> + <li><strong>Handicap Accessible:</strong> %s</li> + <li><strong>Pets Allowed:</strong> %s</li> + <li><strong>Furnished:</strong> %s</li> + </ul>''' % (row[2], row[4], row[3], row[6], row[7], row[8]) + item['pubDate'] = time.localtime() + return item + +def get_listings(min_rent=0, max_rent=5000): + postdata = 'lb_rentStart=%s&lb_rentEnd=%s&%s' % \ + (min_rent, max_rent, BASE_DATA) + listings = BeautifulSoup(urllib2.urlopen(SOURCE_URL, postdata).read()) + listing_block = listings.find('table', width='750', border='1') + rows = listing_block.findAll('tr') + # pop the first, since it's just headings + rows.pop(0) + # Return the following list for each row: + # [Address, City, Term, Type, Beds, Rent, Handicap, Pets, Furnished, URL] + return [[parse_field(f) for f in row.findAll('td')] for row in rows] + +def listings_to_feedobj(listing_matrix): + feed = Feed() + feed.feed['title'] = 'Yale Off-Campus Housing Listings (Unofficial Feed)' + feed.feed['link'] = SOURCE_URL + feed.feed['author'] = 'Elihu Yale' + feed.feed['description'] = 'Listings from Yale\'s Off-Campus Housing Site' + feed.items = [row_to_dict(row) for row in listing_matrix] + return feed + +if __name__ == '__main__': + feedobj = listings_to_feedobj(get_listings()) + if len(sys.argv) > 1: + out = sys.argv[1] + else: + out = 'yale-listings.xml' + feedobj.format_rss2_file(out) \ No newline at end of file
anarchivist/tildebin
e6e1b43fdc50b024a3ef83e647149a59a5e0f113
add ack and svn-authorsfile
diff --git a/README.textile b/README.textile index f120055..401d7db 100644 --- a/README.textile +++ b/README.textile @@ -1,11 +1,13 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. * Blame "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist h2. Possibly incomplete list of scripts and what they do +* ack: Standalone version of "ack, the grep replacemetn":http://github.com/petdance/ack * fits: Launch "FITS, the file information toolset":http://code.google.com/p/fits/ * mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image -* osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. \ No newline at end of file +* osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. +* svn-authorsfile: generate a skeletal git-svn authorsfile from an svn commit log \ No newline at end of file diff --git a/ack b/ack new file mode 100755 index 0000000..7cc459c --- /dev/null +++ b/ack @@ -0,0 +1,2624 @@ +#!/usr/bin/env perl +# +# This file, ack, is generated code. +# Please DO NOT EDIT or send patches for it. +# +# Please take a look at the source from +# http://github.com/petdance/ack +# and submit patches against the individual files +# that build ack. +# + +use warnings; +use strict; + +our $VERSION = '1.92'; +# Check http://betterthangrep.com/ for updates + +# These are all our globals. + + +MAIN: { + if ( $App::Ack::VERSION ne $main::VERSION ) { + App::Ack::die( "Program/library version mismatch\n\t$0 is $main::VERSION\n\t$INC{'App/Ack.pm'} is $App::Ack::VERSION" ); + } + + # Do preliminary arg checking; + my $env_is_usable = 1; + for ( @ARGV ) { + last if ( $_ eq '--' ); + + # Priorities! Get the --thpppt checking out of the way. + /^--th[pt]+t+$/ && App::Ack::_thpppt($_); + + # See if we want to ignore the environment. (Don't tell Al Gore.) + if ( $_ eq '--noenv' ) { + my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV ); + delete @ENV{@keys}; + $env_is_usable = 0; + } + } + unshift( @ARGV, App::Ack::read_ackrc() ) if $env_is_usable; + App::Ack::load_colors(); + + if ( exists $ENV{ACK_SWITCHES} ) { + App::Ack::warn( 'ACK_SWITCHES is no longer supported. Use ACK_OPTIONS.' ); + } + + if ( !@ARGV ) { + App::Ack::show_help(); + exit 1; + } + + main(); +} + +sub main { + my $opt = App::Ack::get_command_line_options(); + + $| = 1 if $opt->{flush}; # Unbuffer the output if flush mode + + if ( App::Ack::input_from_pipe() ) { + # We're going into filter mode + for ( qw( f g l ) ) { + $opt->{$_} and App::Ack::die( "Can't use -$_ when acting as a filter." ); + } + $opt->{show_filename} = 0; + $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt ); + if ( my $nargs = @ARGV ) { + my $s = $nargs == 1 ? '' : 's'; + App::Ack::warn( "Ignoring $nargs argument$s on the command-line while acting as a filter." ); + } + my $res = App::Ack::Resource::Basic->new( '-' ); + App::Ack::search_resource( $res, $opt ); + $res->close(); + exit 0; + } + + my $file_matching = $opt->{f} || $opt->{lines}; + if ( !$file_matching ) { + @ARGV or App::Ack::die( 'No regular expression found.' ); + $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt ); + } + + # check that all regexes do compile fine + App::Ack::check_regex( $_ ) for ( $opt->{regex}, $opt->{G} ); + + my $what = App::Ack::get_starting_points( \@ARGV, $opt ); + my $iter = App::Ack::get_iterator( $what, $opt ); + App::Ack::filetype_setup(); + + my $nmatches = 0; + + App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager}; + if ( $opt->{f} ) { + $nmatches = App::Ack::print_files( $iter, $opt ); + } + elsif ( $opt->{l} || $opt->{count} ) { + $nmatches = App::Ack::print_files_with_matches( $iter, $opt ); + } + else { + $nmatches = App::Ack::print_matches( $iter, $opt ); + } + close $App::Ack::fh; + exit ($nmatches ? 0 : 1); +} + +=head1 NAME + +ack - grep-like text finder + +=head1 SYNOPSIS + + ack [options] PATTERN [FILE...] + ack -f [options] [DIRECTORY...] + +=head1 DESCRIPTION + +Ack is designed as a replacement for 99% of the uses of F<grep>. + +Ack searches the named input FILEs (or standard input if no files are +named, or the file name - is given) for lines containing a match to the +given PATTERN. By default, ack prints the matching lines. + +Ack can also list files that would be searched, without actually searching +them, to let you take advantage of ack's file-type filtering capabilities. + +=head1 FILE SELECTION + +I<ack> is intelligent about the files it searches. It knows about +certain file types, based on both the extension on the file and, +in some cases, the contents of the file. These selections can be +made with the B<--type> option. + +With no file selections, I<ack> only searches files of types that +it recognizes. If you have a file called F<foo.wango>, and I<ack> +doesn't know what a .wango file is, I<ack> won't search it. + +The B<-a> option tells I<ack> to select all files, regardless of +type. + +Some files will never be selected by I<ack>, even with B<-a>, +including: + +=over 4 + +=item * Backup files: Files matching F<#*#> or ending with F<~>. + +=item * Coredumps: Files matching F<core.\d+> + +=back + +However, I<ack> always searches the files given on the command line, +no matter what type. Furthermore, by specifying the B<-u> option all +files will be searched. + +=head1 DIRECTORY SELECTION + +I<ack> descends through the directory tree of the starting directories +specified. However, it will ignore the shadow directories used by +many version control systems, and the build directories used by the +Perl MakeMaker system. You may add or remove a directory from this +list with the B<--[no]ignore-dir> option. The option may be repeated +to add/remove multiple directories from the ignore list. + +For a complete list of directories that do not get searched, run +F<ack --help>. + +=head1 WHEN TO USE GREP + +I<ack> trumps I<grep> as an everyday tool 99% of the time, but don't +throw I<grep> away, because there are times you'll still need it. + +E.g., searching through huge files looking for regexes that can be +expressed with I<grep> syntax should be quicker with I<grep>. + +If your script or parent program uses I<grep> C<--quiet> or +C<--silent> or needs exit 2 on IO error, use I<grep>. + +=head1 OPTIONS + +=over 4 + +=item B<-a>, B<--all> + +Operate on all files, regardless of type (but still skip directories +like F<blib>, F<CVS>, etc.) + +=item B<-A I<NUM>>, B<--after-context=I<NUM>> + +Print I<NUM> lines of trailing context after matching lines. + +=item B<-B I<NUM>>, B<--before-context=I<NUM>> + +Print I<NUM> lines of leading context before matching lines. + +=item B<-C [I<NUM>]>, B<--context[=I<NUM>]> + +Print I<NUM> lines (default 2) of context around matching lines. + +=item B<-c>, B<--count> + +Suppress normal output; instead print a count of matching lines for +each input file. If B<-l> is in effect, it will only show the +number of lines for each file that has lines matching. Without +B<-l>, some line counts may be zeroes. + +=item B<--color>, B<--nocolor> + +B<--color> highlights the matching text. B<--nocolor> supresses +the color. This is on by default unless the output is redirected. + +On Windows, this option is off by default unless the +L<Win32::Console::ANSI> module is installed or the C<ACK_PAGER_COLOR> +environment variable is used. + +=item B<--color-filename=I<color>> + +Sets the color to be used for filenames. + +=item B<--color-match=I<color>> + +Sets the color to be used for matches. + +=item B<--column> + +Show the column number of the first match. This is helpful for editors +that can place your cursor at a given position. + +=item B<--env>, B<--noenv> + +B<--noenv> disables all environment processing. No F<.ackrc> is read +and all environment variables are ignored. By default, F<ack> considers +F<.ackrc> and settings in the environment. + +=item B<--flush> + +B<--flush> flushes output immediately. This is off by default +unless ack is running interactively (when output goes to a pipe +or file). + +=item B<-f> + +Only print the files that would be searched, without actually doing +any searching. PATTERN must not be specified, or it will be taken as +a path to search. + +=item B<--follow>, B<--nofollow> + +Follow or don't follow symlinks, other than whatever starting files +or directories were specified on the command line. + +This is off by default. + +=item B<-G I<REGEX>> + +Only paths matching I<REGEX> are included in the search. The entire +path and filename are matched against I<REGEX>, and I<REGEX> is a +Perl regular expression, not a shell glob. + +The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I<REGEX>. + +=item B<-g I<REGEX>> + +Print files where the relative path + filename matches I<REGEX>. This option is +a convenience shortcut for B<-f> B<-G I<REGEX>>. + +The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I<REGEX>. + +=item B<--group>, B<--nogroup> + +B<--group> groups matches by file name with. This is the default when +used interactively. + +B<--nogroup> prints one result per line, like grep. This is the default +when output is redirected. + +=item B<-H>, B<--with-filename> + +Print the filename for each match. + +=item B<-h>, B<--no-filename> + +Suppress the prefixing of filenames on output when multiple files are +searched. + +=item B<--help> + +Print a short help statement. + +=item B<-i>, B<--ignore-case> + +Ignore case in the search strings. + +This applies only to the PATTERN, not to the regexes given for the B<-g> +and B<-G> options. + +=item B<--[no]ignore-dir=DIRNAME> + +Ignore directory (as CVS, .svn, etc are ignored). May be used multiple times +to ignore multiple directories. For example, mason users may wish to include +B<--ignore-dir=data>. The B<--noignore-dir> option allows users to search +directories which would normally be ignored (perhaps to research the contents +of F<.svn/props> directories). + +=item B<--line=I<NUM>> + +Only print line I<NUM> of each file. Multiple lines can be given with multiple +B<--line> options or as a comma separated list (B<--line=3,5,7>). B<--line=4-7> +also works. The lines are always output in ascending order, no matter the +order given on the command line. + +=item B<-l>, B<--files-with-matches> + +Only print the filenames of matching files, instead of the matching text. + +=item B<-L>, B<--files-without-matches> + +Only print the filenames of files that do I<NOT> match. This is equivalent +to specifying B<-l> and B<-v>. + +=item B<--match I<REGEX>> + +Specify the I<REGEX> explicitly. This is helpful if you don't want to put the +regex as your first argument, e.g. when executing multiple searches over the +same set of files. + + # search for foo and bar in given files + ack file1 t/file* --match foo + ack file1 t/file* --match bar + +=item B<-m=I<NUM>>, B<--max-count=I<NUM>> + +Stop reading a file after I<NUM> matches. + +=item B<--man> + +Print this manual page. + +=item B<-n> + +No descending into subdirectories. + +=item B<-o> + +Show only the part of each line matching PATTERN (turns off text +highlighting) + +=item B<--output=I<expr>> + +Output the evaluation of I<expr> for each line (turns off text +highlighting) + +=item B<--pager=I<program>> + +Direct ack's output through I<program>. This can also be specified +via the C<ACK_PAGER> and C<ACK_PAGER_COLOR> environment variables. + +Using --pager does not suppress grouping and coloring like piping +output on the command-line does. + +=item B<--passthru> + +Prints all lines, whether or not they match the expression. Highlighting +will still work, though, so it can be used to highlight matches while +still seeing the entire file, as in: + + # Watch a log file, and highlight a certain IP address + $ tail -f ~/access.log | ack --passthru 123.45.67.89 + +=item B<--print0> + +Only works in conjunction with -f, -g, -l or -c (filename output). The filenames +are output separated with a null byte instead of the usual newline. This is +helpful when dealing with filenames that contain whitespace, e.g. + + # remove all files of type html + ack -f --html --print0 | xargs -0 rm -f + +=item B<-Q>, B<--literal> + +Quote all metacharacters in PATTERN, it is treated as a literal. + +This applies only to the PATTERN, not to the regexes given for the B<-g> +and B<-G> options. + +=item B<--smart-case>, B<--no-smart-case> + +Ignore case in the search strings if PATTERN contains no uppercase +characters. This is similar to C<smartcase> in vim. This option is +off by default. + +B<-i> always overrides this option. + +This applies only to the PATTERN, not to the regexes given for the +B<-g> and B<-G> options. + +=item B<--sort-files> + +Sorts the found files lexically. Use this if you want your file +listings to be deterministic between runs of I<ack>. + +=item B<--thpppt> + +Display the all-important Bill The Cat logo. Note that the exact +spelling of B<--thpppppt> is not important. It's checked against +a regular expression. + +=item B<--type=TYPE>, B<--type=noTYPE> + +Specify the types of files to include or exclude from a search. +TYPE is a filetype, like I<perl> or I<xml>. B<--type=perl> can +also be specified as B<--perl>, and B<--type=noperl> can be done +as B<--noperl>. + +If a file is of both type "foo" and "bar", specifying --foo and +--nobar will exclude the file, because an exclusion takes precedence +over an inclusion. + +Type specifications can be repeated and are ORed together. + +See I<ack --help=types> for a list of valid types. + +=item B<--type-add I<TYPE>=I<.EXTENSION>[,I<.EXT2>[,...]]> + +Files with the given EXTENSION(s) are recognized as being of (the +existing) type TYPE. See also L</"Defining your own types">. + + +=item B<--type-set I<TYPE>=I<.EXTENSION>[,I<.EXT2>[,...]]> + +Files with the given EXTENSION(s) are recognized as being of type +TYPE. This replaces an existing definition for type TYPE. See also +L</"Defining your own types">. + +=item B<-u>, B<--unrestricted> + +All files and directories (including blib/, core.*, ...) are searched, +nothing is skipped. When both B<-u> and B<--ignore-dir> are used, the +B<--ignore-dir> option has no effect. + +=item B<-v>, B<--invert-match> + +Invert match: select non-matching lines + +This applies only to the PATTERN, not to the regexes given for the B<-g> +and B<-G> options. + +=item B<--version> + +Display version and copyright information. + +=item B<-w>, B<--word-regexp> + +Force PATTERN to match only whole words. The PATTERN is wrapped with +C<\b> metacharacters. + +This applies only to the PATTERN, not to the regexes given for the B<-g> +and B<-G> options. + +=item B<-1> + +Stops after reporting first match of any kind. This is different +from B<--max-count=1> or B<-m1>, where only one match per file is +shown. Also, B<-1> works with B<-f> and B<-g>, where B<-m> does +not. + +=back + +=head1 THE .ackrc FILE + +The F<.ackrc> file contains command-line options that are prepended +to the command line before processing. Multiple options may live +on multiple lines. Lines beginning with a # are ignored. A F<.ackrc> +might look like this: + + # Always sort the files + --sort-files + + # Always color, even if piping to a another program + --color + + # Use "less -r" as my pager + --pager=less -r + +Note that arguments with spaces in them do not need to be quoted, +as they are not interpreted by the shell. Basically, each I<line> +in the F<.ackrc> file is interpreted as one element of C<@ARGV>. + +F<ack> looks in your home directory for the F<.ackrc>. You can +specify another location with the F<ACKRC> variable, below. + +If B<--noenv> is specified on the command line, the F<.ackrc> file +is ignored. + +=head1 Defining your own types + +ack allows you to define your own types in addition to the predefined +types. This is done with command line options that are best put into +an F<.ackrc> file - then you do not have to define your types over and +over again. In the following examples the options will always be shown +on one command line so that they can be easily copy & pasted. + +I<ack --perl foo> searches for foo in all perl files. I<ack --help=types> +tells you, that perl files are files ending +in .pl, .pm, .pod or .t. So what if you would like to include .xs +files as well when searching for --perl files? I<ack --type-add perl=.xs --perl foo> +does this for you. B<--type-add> appends +additional extensions to an existing type. + +If you want to define a new type, or completely redefine an existing +type, then use B<--type-set>. I<ack --type-set +eiffel=.e,.eiffel> defines the type I<eiffel> to include files with +the extensions .e or .eiffel. So to search for all eiffel files +containing the word Bertrand use I<ack --type-set eiffel=.e,.eiffel --eiffel Bertrand>. +As usual, you can also write B<--type=eiffel> +instead of B<--eiffel>. Negation also works, so B<--noeiffel> excludes +all eiffel files from a search. Redefining also works: I<ack --type-set cc=.c,.h> +and I<.xs> files no longer belong to the type I<cc>. + +When defining your own types in the F<.ackrc> file you have to use +the following: + + --type-set=eiffel=.e,.eiffel + +or writing on separate lines + + --type-set + eiffel=.e,.eiffel + +The following does B<NOT> work in the F<.ackrc> file: + + --type-set eiffel=.e,.eiffel + + +In order to see all currently defined types, use I<--help types>, e.g. +I<ack --type-set backup=.bak --type-add perl=.perl --help types> + +Restrictions: + +=over 4 + +=item + +The types 'skipped', 'make', 'binary' and 'text' are considered "builtin" and +cannot be altered. + +=item + +The shebang line recognition of the types 'perl', 'ruby', 'php', 'python', +'shell' and 'xml' cannot be redefined by I<--type-set>, it is always +active. However, the shebang line is only examined for files where the +extension is not recognised. Therefore it is possible to say +I<ack --type-set perl=.perl --type-set foo=.pl,.pm,.pod,.t --perl --nofoo> and +only find your shiny new I<.perl> files (and all files with unrecognized extension +and perl on the shebang line). + +=back + +=head1 ENVIRONMENT VARIABLES + +For commonly-used ack options, environment variables can make life much easier. +These variables are ignored if B<--noenv> is specified on the command line. + +=over 4 + +=item ACKRC + +Specifies the location of the F<.ackrc> file. If this file doesn't +exist, F<ack> looks in the default location. + +=item ACK_OPTIONS + +This variable specifies default options to be placed in front of +any explicit options on the command line. + +=item ACK_COLOR_FILENAME + +Specifies the color of the filename when it's printed in B<--group> +mode. By default, it's "bold green". + +The recognized attributes are clear, reset, dark, bold, underline, +underscore, blink, reverse, concealed black, red, green, yellow, +blue, magenta, on_black, on_red, on_green, on_yellow, on_blue, +on_magenta, on_cyan, and on_white. Case is not significant. +Underline and underscore are equivalent, as are clear and reset. +The color alone sets the foreground color, and on_color sets the +background color. + +This option can also be set with B<--color-filename>. + +=item ACK_COLOR_MATCH + +Specifies the color of the matching text when printed in B<--color> +mode. By default, it's "black on_yellow". + +This option can also be set with B<--color-match>. + +See B<ACK_COLOR_FILENAME> for the color specifications. + +=item ACK_PAGER + +Specifies a pager program, such as C<more>, C<less> or C<most>, to which +ack will send its output. + +Using C<ACK_PAGER> does not suppress grouping and coloring like +piping output on the command-line does, except that on Windows +ack will assume that C<ACK_PAGER> does not support color. + +C<ACK_PAGER_COLOR> overrides C<ACK_PAGER> if both are specified. + +=item ACK_PAGER_COLOR + +Specifies a pager program that understands ANSI color sequences. +Using C<ACK_PAGER_COLOR> does not suppress grouping and coloring +like piping output on the command-line does. + +If you are not on Windows, you never need to use C<ACK_PAGER_COLOR>. + +=back + +=head1 ACK & OTHER TOOLS + +=head2 Vim integration + +F<ack> integrates easily with the Vim text editor. Set this in your +F<.vimrc> to use F<ack> instead of F<grep>: + + set grepprg=ack\ -a + +That examples uses C<-a> to search through all files, but you may +use other default flags. Now you can search with F<ack> and easily +step through the results in Vim: + + :grep Dumper perllib + +=head2 Emacs integration + +Phil Jackson put together an F<ack.el> extension that "provides a +simple compilation mode ... has the ability to guess what files you +want to search for based on the major-mode." + +L<http://www.shellarchive.co.uk/content/emacs.html> + +=head2 TextMate integration + +Pedro Melo is a TextMate user who writes "I spend my day mostly +inside TextMate, and the built-in find-in-project sucks with large +projects. So I hacked a TextMate command that was using find + +grep to use ack. The result is the Search in Project with ack, and +you can find it here: +L<http://www.simplicidade.org/notes/archives/2008/03/search_in_proje.html>" + +=head2 Shell and Return Code + +For greater compatibility with I<grep>, I<ack> in normal use returns +shell return or exit code of 0 only if something is found and 1 if +no match is found. + +(Shell exit code 1 is C<$?=256> in perl with C<system> or backticks.) + +The I<grep> code 2 for errors is not used. + +If C<-f> or C<-g> are specified, then 0 is returned if at least one +file is found. If no files are found, then 1 is returned. + +=cut + +=head1 DEBUGGING ACK PROBLEMS + +If ack gives you output you're not expecting, start with a few simple steps. + +=head2 Use B<--noenv> + +Your environment variables and F<.ackrc> may be doing things you're +not expecting, or forgotten you specified. Use B<--noenv> to ignore +your environment and F<.ackrc>. + +=head2 Use B<-f> to see what files you're scanning + +The reason I created B<-f> in the first place was as a debugging +tool. If ack is not finding matches you think it should find, run +F<ack -f> to see what files are being checked. + +=head1 TIPS + +=head2 Use the F<.ackrc> file. + +The F<.ackrc> is the place to put all your options you use most of +the time but don't want to remember. Put all your --type-add and +--type-set definitions in it. If you like --smart-case, set it +there, too. I also set --sort-files there. + +=head2 Use F<-f> for working with big codesets + +Ack does more than search files. C<ack -f --perl> will create a +list of all the Perl files in a tree, ideal for sending into F<xargs>. +For example: + + # Change all "this" to "that" in all Perl files in a tree. + ack -f --perl | xargs perl -p -i -e's/this/that/g' + +or if you prefer: + + perl -p -i -e's/this/thatg/' $(ack -f --perl) + +=head2 Use F<-Q> when in doubt about metacharacters + +If you're searching for something with a regular expression +metacharacter, most often a period in a filename or IP address, add +the -Q to avoid false positives without all the backslashing. See +the following example for more... + +=head2 Use ack to watch log files + +Here's one I used the other day to find trouble spots for a website +visitor. The user had a problem loading F<troublesome.gif>, so I +took the access log and scanned it with ack twice. + + ack -Q aa.bb.cc.dd /path/to/access.log | ack -Q -B5 troublesome.gif + +The first ack finds only the lines in the Apache log for the given +IP. The second finds the match on my troublesome GIF, and shows +the previous five lines from the log in each case. + +=head2 Share your knowledge + +Join the ack-users mailing list. Send me your tips and I may add +them here. + +=head1 FAQ + +=head2 Why isn't ack finding a match in (some file)? + +Probably because it's of a type that ack doesn't recognize. + +ack's searching behavior is driven by filetype. If ack doesn't +know what kind of file it is, ack ignores it. + +If you want ack to search files that it doesn't recognize, use the +C<-a> switch. + +If you want ack to search every file, even ones that it always +ignores like coredumps and backup files, use the C<-u> switch. + +=head2 Why does ack ignore unknown files by default? + +ack is designed by a programmer, for programmers, for searching +large trees of code. Most codebases have a lot files in them which +aren't source files (like compiled object files, source control +metadata, etc), and grep wastes a lot of time searching through all +of those as well and returning matches from those files. + +That's why ack's behavior of not searching things it doesn't recognize +is one of its greatest strengths: the speed you get from only +searching the things that you want to be looking at. + +=head2 Wouldn't it be great if F<ack> did search & replace? + +No, ack will always be read-only. Perl has a perfectly good way +to do search & replace in files, using the C<-i>, C<-p> and C<-n> +switches. + +You can certainly use ack to select your files to update. For +example, to change all "foo" to "bar" in all PHP files, you can do +this form the Unix shell: + + $ perl -i -p -e's/foo/bar/g' $(ack -f --php) + +=head2 Can you make ack recognize F<.xyz> files? + +That's an enhancement. Please see the section in the manual about +enhancements. + +=head2 There's already a program/package called ack. + +Yes, I know. + +=head2 Why is it called ack if it's called ack-grep? + +The name of the program is "ack". Some packagers have called it +"ack-grep" when creating packages because there's already a package +out there called "ack" that has nothing to do with this ack. + +I suggest you rename your ack-grep install to "ack" because one of +the crucial benefits of ack is having a name that's so short and +simple to type. + +=head1 AUTHOR + +Andy Lester, C<< <andy at petdance.com> >> + +=head1 BUGS + +Please report any bugs or feature requests to the issues list at +Github: L<http://github.com/petdance/ack/issues> + +=head1 ENHANCEMENTS + +All enhancement requests MUST first be posted to the ack-users +mailing list at L<http://groups.google.com/group/ack-users>. I +will not consider a request without it first getting seen by other +ack users. This includes requests for new filetypes. + +There is a list of enhancements I want to make to F<ack> in the ack +issues list at Github: L<http://github.com/petdance/ack/issues> + +Patches are always welcome, but patches with tests get the most +attention. + +=head1 SUPPORT + +Support for and information about F<ack> can be found at: + +=over 4 + +=item * The ack homepage + +L<http://betterthangrep.com/> + +=item * The ack issues list at Github + +L<http://github.com/petdance/ack/issues> + +=item * AnnoCPAN: Annotated CPAN documentation + +L<http://annocpan.org/dist/ack> + +=item * CPAN Ratings + +L<http://cpanratings.perl.org/d/ack> + +=item * Search CPAN + +L<http://search.cpan.org/dist/ack> + +=item * Git source repository + +L<http://github.com/petdance/ack> + +=back + +=head1 ACKNOWLEDGEMENTS + +How appropriate to have I<ack>nowledgements! + +Thanks to everyone who has contributed to ack in any way, including +Packy Anderson, +JR Boyens, +Dan Sully, +Ryan Niebur, +Kent Fredric, +Mike Morearty, +Ingmar Vanhassel, +Eric Van Dewoestine, +Sitaram Chamarty, +Adam James, +Richard Carlsson, +Pedro Melo, +AJ Schuster, +Phil Jackson, +Michael Schwern, +Jan Dubois, +Christopher J. Madsen, +Matthew Wickline, +David Dyck, +Jason Porritt, +Jjgod Jiang, +Thomas Klausner, +Uri Guttman, +Peter Lewis, +Kevin Riggle, +Ori Avtalion, +Torsten Blix, +Nigel Metheringham, +GE<aacute>bor SzabE<oacute>, +Tod Hagan, +Michael Hendricks, +E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason, +Piers Cawley, +Stephen Steneker, +Elias Lutfallah, +Mark Leighton Fisher, +Matt Diephouse, +Christian Jaeger, +Bill Sully, +Bill Ricker, +David Golden, +Nilson Santos F. Jr, +Elliot Shank, +Merijn Broeren, +Uwe Voelker, +Rick Scott, +Ask BjE<oslash>rn Hansen, +Jerry Gay, +Will Coleda, +Mike O'Regan, +Slaven ReziE<0x107>, +Mark Stosberg, +David Alan Pisoni, +Adriano Ferreira, +James Keenan, +Leland Johnson, +Ricardo Signes +and Pete Krawczyk. + +=head1 COPYRIGHT & LICENSE + +Copyright 2005-2009 Andy Lester. + +This program is free software; you can redistribute it and/or modify +it under the terms of either: + +=over 4 + +=item * the GNU General Public License as published by the Free +Software Foundation; either version 1, or (at your option) any later +version, or + +=item * the Artistic License version 2.0. + +=back + +=cut +package File::Next; + +use strict; +use warnings; + + +our $VERSION = '1.06'; + + + +use File::Spec (); + + +our $name; # name of the current file +our $dir; # dir of the current file + +our %files_defaults; +our %skip_dirs; + +BEGIN { + %files_defaults = ( + file_filter => undef, + descend_filter => undef, + error_handler => sub { CORE::die @_ }, + sort_files => undef, + follow_symlinks => 1, + ); + %skip_dirs = map {($_,1)} (File::Spec->curdir, File::Spec->updir); +} + + +sub files { + ($_[0] eq __PACKAGE__) && die 'File::Next::files must not be invoked as File::Next->files'; + + my ($parms,@queue) = _setup( \%files_defaults, @_ ); + my $filter = $parms->{file_filter}; + + return sub { + while (@queue) { + my ($dir,$file,$fullpath) = splice( @queue, 0, 3 ); + if ( -f $fullpath ) { + if ( $filter ) { + local $_ = $file; + local $File::Next::dir = $dir; + local $File::Next::name = $fullpath; + next if not $filter->(); + } + return wantarray ? ($dir,$file,$fullpath) : $fullpath; + } + elsif ( -d _ ) { + unshift( @queue, _candidate_files( $parms, $fullpath ) ); + } + } # while + + return; + }; # iterator +} + + + + + + + +sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] } +sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] } + +sub reslash { + my $path = shift; + + my @parts = split( /\//, $path ); + + return $path if @parts < 2; + + return File::Spec->catfile( @parts ); +} + + + +sub _setup { + my $defaults = shift; + my $passed_parms = ref $_[0] eq 'HASH' ? {%{+shift}} : {}; # copy parm hash + + my %passed_parms = %{$passed_parms}; + + my $parms = {}; + for my $key ( keys %{$defaults} ) { + $parms->{$key} = + exists $passed_parms{$key} + ? delete $passed_parms{$key} + : $defaults->{$key}; + } + + # Any leftover keys are bogus + for my $badkey ( keys %passed_parms ) { + my $sub = (caller(1))[3]; + $parms->{error_handler}->( "Invalid option passed to $sub(): $badkey" ); + } + + # If it's not a code ref, assume standard sort + if ( $parms->{sort_files} && ( ref($parms->{sort_files}) ne 'CODE' ) ) { + $parms->{sort_files} = \&sort_standard; + } + my @queue; + + for ( @_ ) { + my $start = reslash( $_ ); + if (-d $start) { + push @queue, ($start,undef,$start); + } + else { + push @queue, (undef,$start,$start); + } + } + + return ($parms,@queue); +} + + +sub _candidate_files { + my $parms = shift; + my $dir = shift; + + my $dh; + if ( !opendir $dh, $dir ) { + $parms->{error_handler}->( "$dir: $!" ); + return; + } + + my @newfiles; + my $descend_filter = $parms->{descend_filter}; + my $follow_symlinks = $parms->{follow_symlinks}; + my $sort_sub = $parms->{sort_files}; + + for my $file ( grep { !exists $skip_dirs{$_} } readdir $dh ) { + my $has_stat; + + # Only do directory checking if we have a descend_filter + my $fullpath = File::Spec->catdir( $dir, $file ); + if ( !$follow_symlinks ) { + next if -l $fullpath; + $has_stat = 1; + } + + if ( $descend_filter ) { + if ( $has_stat ? (-d _) : (-d $fullpath) ) { + local $File::Next::dir = $fullpath; + local $_ = $file; + next if not $descend_filter->(); + } + } + if ( $sort_sub ) { + push( @newfiles, [ $dir, $file, $fullpath ] ); + } + else { + push( @newfiles, $dir, $file, $fullpath ); + } + } + closedir $dh; + + if ( $sort_sub ) { + return map { @{$_} } sort $sort_sub @newfiles; + } + + return @newfiles; +} + + +1; # End of File::Next +package App::Ack; + +use warnings; +use strict; + + + + +our $VERSION; +our $COPYRIGHT; +BEGIN { + $VERSION = '1.92'; + $COPYRIGHT = 'Copyright 2005-2009 Andy Lester.'; +} + +our $fh; + +BEGIN { + $fh = *STDOUT; +} + + +our %types; +our %type_wanted; +our %mappings; +our %ignore_dirs; + +our $input_from_pipe; +our $output_to_pipe; + +our $dir_sep_chars; +our $is_cygwin; +our $is_windows; + +use File::Spec (); +use File::Glob ':glob'; +use Getopt::Long (); + +BEGIN { + %ignore_dirs = ( + '.bzr' => 'Bazaar', + '.cdv' => 'Codeville', + '~.dep' => 'Interface Builder', + '~.dot' => 'Interface Builder', + '~.nib' => 'Interface Builder', + '~.plst' => 'Interface Builder', + '.git' => 'Git', + '.hg' => 'Mercurial', + '.pc' => 'quilt', + '.svn' => 'Subversion', + blib => 'Perl module building', + CVS => 'CVS', + RCS => 'RCS', + SCCS => 'SCCS', + _darcs => 'darcs', + _sgbak => 'Vault/Fortress', + 'autom4te.cache' => 'autoconf', + 'cover_db' => 'Devel::Cover', + _build => 'Module::Build', + ); + + %mappings = ( + actionscript => [qw( as mxml )], + ada => [qw( ada adb ads )], + asm => [qw( asm s )], + batch => [qw( bat cmd )], + binary => q{Binary files, as defined by Perl's -B op (default: off)}, + cc => [qw( c h xs )], + cfmx => [qw( cfc cfm cfml )], + cpp => [qw( cpp cc cxx m hpp hh h hxx )], + csharp => [qw( cs )], + css => [qw( css )], + elisp => [qw( el )], + erlang => [qw( erl hrl )], + fortran => [qw( f f77 f90 f95 f03 for ftn fpp )], + haskell => [qw( hs lhs )], + hh => [qw( h )], + html => [qw( htm html shtml xhtml )], + java => [qw( java properties )], + js => [qw( js )], + jsp => [qw( jsp jspx jhtm jhtml )], + lisp => [qw( lisp lsp )], + lua => [qw( lua )], + make => q{Makefiles}, + mason => [qw( mas mhtml mpl mtxt )], + objc => [qw( m h )], + objcpp => [qw( mm h )], + ocaml => [qw( ml mli )], + parrot => [qw( pir pasm pmc ops pod pg tg )], + perl => [qw( pl pm pod t )], + php => [qw( php phpt php3 php4 php5 phtml)], + plone => [qw( pt cpt metadata cpy py )], + python => [qw( py )], + rake => q{Rakefiles}, + ruby => [qw( rb rhtml rjs rxml erb rake )], + scala => [qw( scala )], + scheme => [qw( scm ss )], + shell => [qw( sh bash csh tcsh ksh zsh )], + skipped => q{Files, but not directories, normally skipped by ack (default: off)}, + smalltalk => [qw( st )], + sql => [qw( sql ctl )], + tcl => [qw( tcl itcl itk )], + tex => [qw( tex cls sty )], + text => q{Text files, as defined by Perl's -T op (default: off)}, + tt => [qw( tt tt2 ttml )], + vb => [qw( bas cls frm ctl vb resx )], + vim => [qw( vim )], + yaml => [qw( yaml yml )], + xml => [qw( xml dtd xslt ent )], + ); + + while ( my ($type,$exts) = each %mappings ) { + if ( ref $exts ) { + for my $ext ( @{$exts} ) { + push( @{$types{$ext}}, $type ); + } + } + } + + # These have to be checked before any filehandle diddling. + $output_to_pipe = not -t *STDOUT; + $input_from_pipe = -p STDIN; + + $is_cygwin = ($^O eq 'cygwin'); + $is_windows = ($^O =~ /MSWin32/); + $dir_sep_chars = $is_windows ? quotemeta( '\\/' ) : quotemeta( File::Spec->catfile( '', '' ) ); +} + + +sub read_ackrc { + my @files = ( $ENV{ACKRC} ); + my @dirs = + $is_windows + ? ( $ENV{HOME}, $ENV{USERPROFILE} ) + : ( '~', $ENV{HOME} ); + for my $dir ( grep { defined } @dirs ) { + for my $file ( '.ackrc', '_ackrc' ) { + push( @files, bsd_glob( "$dir/$file", GLOB_TILDE ) ); + } + } + for my $filename ( @files ) { + if ( defined $filename && -e $filename ) { + open( my $fh, '<', $filename ) or App::Ack::die( "$filename: $!\n" ); + my @lines = grep { /./ && !/^\s*#/ } <$fh>; + chomp @lines; + close $fh or App::Ack::die( "$filename: $!\n" ); + + return @lines; + } + } + + return; +} + + +sub get_command_line_options { + my %opt = ( + pager => $ENV{ACK_PAGER_COLOR} || $ENV{ACK_PAGER}, + ); + + my $getopt_specs = { + 1 => sub { $opt{1} = $opt{m} = 1 }, + 'A|after-context=i' => \$opt{after_context}, + 'B|before-context=i' => \$opt{before_context}, + 'C|context:i' => sub { shift; my $val = shift; $opt{before_context} = $opt{after_context} = ($val || 2) }, + 'a|all-types' => \$opt{all}, + 'break!' => \$opt{break}, + c => \$opt{count}, + 'color|colour!' => \$opt{color}, + 'color-match=s' => \$ENV{ACK_COLOR_MATCH}, + 'color-filename=s' => \$ENV{ACK_COLOR_FILENAME}, + 'column!' => \$opt{column}, + count => \$opt{count}, + 'env!' => sub { }, # ignore this option, it is handled beforehand + f => \$opt{f}, + flush => \$opt{flush}, + 'follow!' => \$opt{follow}, + 'g=s' => sub { shift; $opt{G} = shift; $opt{f} = 1 }, + 'G=s' => \$opt{G}, + 'group!' => sub { shift; $opt{heading} = $opt{break} = shift }, + 'heading!' => \$opt{heading}, + 'h|no-filename' => \$opt{h}, + 'H|with-filename' => \$opt{H}, + 'i|ignore-case' => \$opt{i}, + 'lines=s' => sub { shift; my $val = shift; push @{$opt{lines}}, $val }, + 'l|files-with-matches' => \$opt{l}, + 'L|files-without-matches' => sub { $opt{l} = $opt{v} = 1 }, + 'm|max-count=i' => \$opt{m}, + 'match=s' => \$opt{regex}, + 'n|no-recurse' => \$opt{n}, + o => sub { $opt{output} = '$&' }, + 'output=s' => \$opt{output}, + 'pager=s' => \$opt{pager}, + 'nopager' => sub { $opt{pager} = undef }, + 'passthru' => \$opt{passthru}, + 'print0' => \$opt{print0}, + 'Q|literal' => \$opt{Q}, + 'r|R|recurse' => sub {}, + 'smart-case!' => \$opt{smart_case}, + 'sort-files' => \$opt{sort_files}, + 'u|unrestricted' => \$opt{u}, + 'v|invert-match' => \$opt{v}, + 'w|word-regexp' => \$opt{w}, + + 'ignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); $ignore_dirs{$dir} = '--ignore-dirs' }, + 'noignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); delete $ignore_dirs{$dir} }, + + 'version' => sub { print_version_statement(); exit 1; }, + 'help|?:s' => sub { shift; show_help(@_); exit; }, + 'help-types'=> sub { show_help_types(); exit; }, + 'man' => sub { require Pod::Usage; Pod::Usage::pod2usage({-verbose => 2}); exit; }, + + 'type=s' => sub { + # Whatever --type=xxx they specify, set it manually in the hash + my $dummy = shift; + my $type = shift; + my $wanted = ($type =~ s/^no//) ? 0 : 1; # must not be undef later + + if ( exists $type_wanted{ $type } ) { + $type_wanted{ $type } = $wanted; + } + else { + App::Ack::die( qq{Unknown --type "$type"} ); + } + }, # type sub + }; + + # Stick any default switches at the beginning, so they can be overridden + # by the command line switches. + unshift @ARGV, split( ' ', $ENV{ACK_OPTIONS} ) if defined $ENV{ACK_OPTIONS}; + + # first pass through options, looking for type definitions + def_types_from_ARGV(); + + for my $i ( filetypes_supported() ) { + $getopt_specs->{ "$i!" } = \$type_wanted{ $i }; + } + + + my $parser = Getopt::Long::Parser->new(); + $parser->configure( 'bundling', 'no_ignore_case', ); + $parser->getoptions( %{$getopt_specs} ) or + App::Ack::die( 'See ack --help, ack --help-types or ack --man for options.' ); + + my $to_screen = not output_to_pipe(); + my %defaults = ( + all => 0, + color => $to_screen, + follow => 0, + break => $to_screen, + heading => $to_screen, + before_context => 0, + after_context => 0, + ); + if ( $is_windows && $defaults{color} && not $ENV{ACK_PAGER_COLOR} ) { + if ( $ENV{ACK_PAGER} || not eval { require Win32::Console::ANSI } ) { + $defaults{color} = 0; + } + } + if ( $to_screen && $ENV{ACK_PAGER_COLOR} ) { + $defaults{color} = 1; + } + + while ( my ($key,$value) = each %defaults ) { + if ( not defined $opt{$key} ) { + $opt{$key} = $value; + } + } + + if ( defined $opt{m} && $opt{m} <= 0 ) { + App::Ack::die( '-m must be greater than zero' ); + } + + for ( qw( before_context after_context ) ) { + if ( defined $opt{$_} && $opt{$_} < 0 ) { + App::Ack::die( "--$_ may not be negative" ); + } + } + + if ( defined( my $val = $opt{output} ) ) { + $opt{output} = eval qq[ sub { "$val" } ]; + } + if ( defined( my $l = $opt{lines} ) ) { + # --line=1 --line=5 is equivalent to --line=1,5 + my @lines = split( /,/, join( ',', @{$l} ) ); + + # --line=1-3 is equivalent to --line=1,2,3 + @lines = map { + my @ret; + if ( /-/ ) { + my ($from, $to) = split /-/, $_; + if ( $from > $to ) { + App::Ack::warn( "ignoring --line=$from-$to" ); + @ret = (); + } + else { + @ret = ( $from .. $to ); + } + } + else { + @ret = ( $_ ); + }; + @ret + } @lines; + + if ( @lines ) { + my %uniq; + @uniq{ @lines } = (); + $opt{lines} = [ sort { $a <=> $b } keys %uniq ]; # numerical sort and each line occurs only once! + } + else { + # happens if there are only ignored --line directives + App::Ack::die( 'All --line options are invalid.' ); + } + } + + return \%opt; +} + + +sub def_types_from_ARGV { + my @typedef; + + my $parser = Getopt::Long::Parser->new(); + # pass_through => leave unrecognized command line arguments alone + # no_auto_abbrev => otherwise -c is expanded and not left alone + $parser->configure( 'no_ignore_case', 'pass_through', 'no_auto_abbrev' ); + $parser->getoptions( + 'type-set=s' => sub { shift; push @typedef, ['c', shift] }, + 'type-add=s' => sub { shift; push @typedef, ['a', shift] }, + ) or App::Ack::die( 'See ack --help or ack --man for options.' ); + + for my $td (@typedef) { + my ($type, $ext) = split /=/, $td->[1]; + + if ( $td->[0] eq 'c' ) { + # type-set + if ( exists $mappings{$type} ) { + # can't redefine types 'make', 'skipped', 'text' and 'binary' + App::Ack::die( qq{--type-set: Builtin type "$type" cannot be changed.} ) + if ref $mappings{$type} ne 'ARRAY'; + + delete_type($type); + } + } + else { + # type-add + + # can't append to types 'make', 'skipped', 'text' and 'binary' + App::Ack::die( qq{--type-add: Builtin type "$type" cannot be changed.} ) + if exists $mappings{$type} && ref $mappings{$type} ne 'ARRAY'; + + App::Ack::warn( qq{--type-add: Type "$type" does not exist, creating with "$ext" ...} ) + unless exists $mappings{$type}; + } + + my @exts = split /,/, $ext; + s/^\.// for @exts; + + if ( !exists $mappings{$type} || ref($mappings{$type}) eq 'ARRAY' ) { + push @{$mappings{$type}}, @exts; + for my $e ( @exts ) { + push @{$types{$e}}, $type; + } + } + else { + App::Ack::die( qq{Cannot append to type "$type".} ); + } + } + + return; +} + + +sub delete_type { + my $type = shift; + + App::Ack::die( qq{Internal error: Cannot delete builtin type "$type".} ) + unless ref $mappings{$type} eq 'ARRAY'; + + delete $mappings{$type}; + delete $type_wanted{$type}; + for my $ext ( keys %types ) { + $types{$ext} = [ grep { $_ ne $type } @{$types{$ext}} ]; + } +} + + +sub ignoredir_filter { + return !exists $ignore_dirs{$_}; +} + + +sub remove_dir_sep { + my $path = shift; + $path =~ s/[$dir_sep_chars]$//; + + return $path; +} + + +use constant TEXT => 'text'; + +sub filetypes { + my $filename = shift; + + my $basename = $filename; + $basename =~ s{.*[$dir_sep_chars]}{}; + + return 'skipped' unless is_searchable( $basename ); + + my $lc_basename = lc $basename; + return ('make',TEXT) if $lc_basename eq 'makefile'; + return ('rake','ruby',TEXT) if $lc_basename eq 'rakefile'; + + # If there's an extension, look it up + if ( $filename =~ m{\.([^\.$dir_sep_chars]+)$}o ) { + my $ref = $types{lc $1}; + return (@{$ref},TEXT) if $ref; + } + + # At this point, we can't tell from just the name. Now we have to + # open it and look inside. + + return unless -e $filename; + # From Elliot Shank: + # I can't see any reason that -r would fail on these-- the ACLs look + # fine, and no program has any of them open, so the busted Windows + # file locking model isn't getting in there. If I comment the if + # statement out, everything works fine + # So, for cygwin, don't bother trying to check for readability. + if ( !$is_cygwin ) { + if ( !-r $filename ) { + App::Ack::warn( "$filename: Permission denied" ); + return; + } + } + + return 'binary' if -B $filename; + + # If there's no extension, or we don't recognize it, check the shebang line + my $fh; + if ( !open( $fh, '<', $filename ) ) { + App::Ack::warn( "$filename: $!" ); + return; + } + my $header = <$fh>; + close $fh; + + if ( $header =~ /^#!/ ) { + return ($1,TEXT) if $header =~ /\b(ruby|p(?:erl|hp|ython))\b/; + return ('shell',TEXT) if $header =~ /\b(?:ba|t?c|k|z)?sh\b/; + } + else { + return ('xml',TEXT) if $header =~ /\Q<?xml /i; + } + + return (TEXT); +} + + +sub is_searchable { + my $filename = shift; + + # If these are updated, update the --help message + return if $filename =~ /[.]bak$/; + return if $filename =~ /~$/; + return if $filename =~ m{^#.*#$}o; + return if $filename =~ m{^core\.\d+$}o; + return if $filename =~ m{[._].*\.swp$}o; + + return 1; +} + + +sub build_regex { + my $str = shift; + my $opt = shift; + + $str = quotemeta( $str ) if $opt->{Q}; + if ( $opt->{w} ) { + $str = "\\b$str" if $str =~ /^\w/; + $str = "$str\\b" if $str =~ /\w$/; + } + + my $regex_is_lc = $str eq lc $str; + if ( $opt->{i} || ($opt->{smart_case} && $regex_is_lc) ) { + $str = "(?i)$str"; + } + + return $str; +} + + +sub check_regex { + my $regex = shift; + + return unless defined $regex; + + eval { qr/$regex/ }; + if ($@) { + (my $error = $@) =~ s/ at \S+ line \d+.*//; + chomp($error); + App::Ack::die( "Invalid regex '$regex':\n $error" ); + } + + return; +} + + + + +sub warn { + return CORE::warn( _my_program(), ': ', @_, "\n" ); +} + + +sub die { + return CORE::die( _my_program(), ': ', @_, "\n" ); +} + +sub _my_program { + require File::Basename; + return File::Basename::basename( $0 ); +} + + + +sub filetypes_supported { + return keys %mappings; +} + +sub _get_thpppt { + my $y = q{_ /|,\\'!.x',=(www)=, U }; + $y =~ tr/,x!w/\nOo_/; + return $y; +} + +sub _thpppt { + my $y = _get_thpppt(); + App::Ack::print( "$y ack $_[0]!\n" ); + exit 0; +} + +sub _key { + my $str = lc shift; + $str =~ s/[^a-z]//g; + + return $str; +} + + +sub show_help { + my $help_arg = shift || 0; + + return show_help_types() if $help_arg =~ /^types?/; + + my $ignore_dirs = _listify( sort { _key($a) cmp _key($b) } keys %ignore_dirs ); + + App::Ack::print( <<"END_OF_HELP" ); +Usage: ack [OPTION]... PATTERN [FILE] + +Search for PATTERN in each source file in the tree from cwd on down. +If [FILES] is specified, then only those files/directories are checked. +ack may also search STDIN, but only if no FILE are specified, or if +one of FILES is "-". + +Default switches may be specified in ACK_OPTIONS environment variable or +an .ackrc file. If you want no dependency on the environment, turn it +off with --noenv. + +Example: ack -i select + +Searching: + -i, --ignore-case Ignore case distinctions in PATTERN + --[no]smart-case Ignore case distinctions in PATTERN, + only if PATTERN contains no upper case + Ignored if -i is specified + -v, --invert-match Invert match: select non-matching lines + -w, --word-regexp Force PATTERN to match only whole words + -Q, --literal Quote all metacharacters; PATTERN is literal + +Search output: + --line=NUM Only print line(s) NUM of each file + -l, --files-with-matches + Only print filenames containing matches + -L, --files-without-matches + Only print filenames with no matches + -o Show only the part of a line matching PATTERN + (turns off text highlighting) + --passthru Print all lines, whether matching or not + --output=expr Output the evaluation of expr for each line + (turns off text highlighting) + --match PATTERN Specify PATTERN explicitly. + -m, --max-count=NUM Stop searching in each file after NUM matches + -1 Stop searching after one match of any kind + -H, --with-filename Print the filename for each match + -h, --no-filename Suppress the prefixing filename on output + -c, --count Show number of lines matching per file + --column Show the column number of the first match + + -A NUM, --after-context=NUM + Print NUM lines of trailing context after matching + lines. + -B NUM, --before-context=NUM + Print NUM lines of leading context before matching + lines. + -C [NUM], --context[=NUM] + Print NUM lines (default 2) of output context. + + --print0 Print null byte as separator between filenames, + only works with -f, -g, -l, -L or -c. + +File presentation: + --pager=COMMAND Pipes all ack output through COMMAND. For example, + --pager="less -R". Ignored if output is redirected. + --nopager Do not send output through a pager. Cancels any + setting in ~/.ackrc, ACK_PAGER or ACK_PAGER_COLOR. + --[no]heading Print a filename heading above each file's results. + (default: on when used interactively) + --[no]break Print a break between results from different files. + (default: on when used interactively) + --group Same as --heading --break + --nogroup Same as --noheading --nobreak + --[no]color Highlight the matching text (default: on unless + output is redirected, or on Windows) + --[no]colour Same as --[no]color + --color-filename=COLOR + --color-match=COLOR Set the color for matches and filenames. + --flush Flush output immediately, even when ack is used + non-interactively (when output goes to a pipe or + file). + +File finding: + -f Only print the files found, without searching. + The PATTERN must not be specified. + -g REGEX Same as -f, but only print files matching REGEX. + --sort-files Sort the found files lexically. + +File inclusion/exclusion: + -a, --all-types All file types searched; + Ignores CVS, .svn and other ignored directories + -u, --unrestricted All files and directories searched + --[no]ignore-dir=name Add/Remove directory from the list of ignored dirs + -r, -R, --recurse Recurse into subdirectories (ack's default behavior) + -n, --no-recurse No descending into subdirectories + -G REGEX Only search files that match REGEX + + --perl Include only Perl files. + --type=perl Include only Perl files. + --noperl Exclude Perl files. + --type=noperl Exclude Perl files. + See "ack --help type" for supported filetypes. + + --type-set TYPE=.EXTENSION[,.EXT2[,...]] + Files with the given EXTENSION(s) are recognized as + being of type TYPE. This replaces an existing + definition for type TYPE. + --type-add TYPE=.EXTENSION[,.EXT2[,...]] + Files with the given EXTENSION(s) are recognized as + being of (the existing) type TYPE + + --[no]follow Follow symlinks. Default is off. + + Directories ignored by default: + $ignore_dirs + + Files not checked for type: + /~\$/ - Unix backup files + /#.+#\$/ - Emacs swap files + /[._].*\\.swp\$/ - Vi(m) swap files + /core\\.\\d+\$/ - core dumps + +Miscellaneous: + --noenv Ignore environment variables and ~/.ackrc + --help This help + --man Man page + --version Display version & copyright + --thpppt Bill the Cat + +Exit status is 0 if match, 1 if no match. + +This is version $VERSION of ack. +END_OF_HELP + + return; + } + + + +sub show_help_types { + App::Ack::print( <<'END_OF_HELP' ); +Usage: ack [OPTION]... PATTERN [FILES] + +The following is the list of filetypes supported by ack. You can +specify a file type with the --type=TYPE format, or the --TYPE +format. For example, both --type=perl and --perl work. + +Note that some extensions may appear in multiple types. For example, +.pod files are both Perl and Parrot. + +END_OF_HELP + + my @types = filetypes_supported(); + my $maxlen = 0; + for ( @types ) { + $maxlen = length if $maxlen < length; + } + for my $type ( sort @types ) { + next if $type =~ /^-/; # Stuff to not show + my $ext_list = $mappings{$type}; + + if ( ref $ext_list ) { + $ext_list = join( ' ', map { ".$_" } @{$ext_list} ); + } + App::Ack::print( sprintf( " --[no]%-*.*s %s\n", $maxlen, $maxlen, $type, $ext_list ) ); + } + + return; +} + +sub _listify { + my @whats = @_; + + return '' if !@whats; + + my $end = pop @whats; + my $str = @whats ? join( ', ', @whats ) . " and $end" : $end; + + no warnings 'once'; + require Text::Wrap; + $Text::Wrap::columns = 75; + return Text::Wrap::wrap( '', ' ', $str ); +} + + +sub get_version_statement { + require Config; + + my $copyright = get_copyright(); + my $this_perl = $Config::Config{perlpath}; + if ($^O ne 'VMS') { + my $ext = $Config::Config{_exe}; + $this_perl .= $ext unless $this_perl =~ m/$ext$/i; + } + my $ver = sprintf( '%vd', $^V ); + + return <<"END_OF_VERSION"; +ack $VERSION +Running under Perl $ver at $this_perl + +$copyright + +This program is free software; you can redistribute it and/or modify +it under the terms of either: the GNU General Public License as +published by the Free Software Foundation; or the Artistic License. +END_OF_VERSION +} + + +sub print_version_statement { + App::Ack::print( get_version_statement() ); + + return; +} + + +sub get_copyright { + return $COPYRIGHT; +} + + +sub load_colors { + eval 'use Term::ANSIColor ()'; + + $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow'; + $ENV{ACK_COLOR_FILENAME} ||= 'bold green'; + + return; +} + + +sub is_interesting { + return if /^\./; + + my $include; + + for my $type ( filetypes( $File::Next::name ) ) { + if ( defined $type_wanted{$type} ) { + if ( $type_wanted{$type} ) { + $include = 1; + } + else { + return; + } + } + } + + return $include; +} + + + +# print subs added in order to make it easy for a third party +# module (such as App::Wack) to redefine the display methods +# and show the results in a different way. +sub print { print {$fh} @_ } +sub print_first_filename { App::Ack::print( $_[0], "\n" ) } +sub print_blank_line { App::Ack::print( "\n" ) } +sub print_separator { App::Ack::print( "--\n" ) } +sub print_filename { App::Ack::print( $_[0], $_[1] ) } +sub print_line_no { App::Ack::print( $_[0], $_[1] ) } +sub print_column_no { App::Ack::print( $_[0], $_[1] ) } +sub print_count { + my $filename = shift; + my $nmatches = shift; + my $ors = shift; + my $count = shift; + + App::Ack::print( $filename ); + App::Ack::print( ':', $nmatches ) if $count; + App::Ack::print( $ors ); +} + +sub print_count0 { + my $filename = shift; + my $ors = shift; + + App::Ack::print( $filename, ':0', $ors ); +} + + + +{ + my $filename; + my $regex; + my $display_filename; + + my $keep_context; + + my $last_output_line; # number of the last line that has been output + my $any_output; # has there been any output for the current file yet + my $context_overall_output_count; # has there been any output at all + +sub search_resource { + my $res = shift; + my $opt = shift; + + $filename = $res->name(); + + my $v = $opt->{v}; + my $passthru = $opt->{passthru}; + my $max = $opt->{m}; + my $nmatches = 0; + + $display_filename = undef; + + # for --line processing + my $has_lines = 0; + my @lines; + if ( defined $opt->{lines} ) { + $has_lines = 1; + @lines = ( @{$opt->{lines}}, -1 ); + undef $regex; # Don't match when printing matching line + } + else { + $regex = qr/$opt->{regex}/; + } + + # for context processing + $last_output_line = -1; + $any_output = 0; + my $before_context = $opt->{before_context}; + my $after_context = $opt->{after_context}; + + $keep_context = ($before_context || $after_context) && !$passthru; + + my @before; + my $before_starts_at_line; + my $after = 0; # number of lines still to print after a match + + while ( $res->next_text ) { + # XXX Optimize away the case when there are no more @lines to find. + # XXX $has_lines, $passthru and $v never change. Optimize. + if ( $has_lines + ? $. != $lines[0] # $lines[0] should be a scalar + : $v ? m/$regex/ : !m/$regex/ ) { + if ( $passthru ) { + App::Ack::print( $_ ); + next; + } + + if ( $keep_context ) { + if ( $after ) { + print_match_or_context( $opt, 0, $., $-[0], $+[0], $_ ); + $after--; + } + elsif ( $before_context ) { + if ( @before ) { + if ( @before >= $before_context ) { + shift @before; + ++$before_starts_at_line; + } + } + else { + $before_starts_at_line = $.; + } + push @before, $_; + } + last if $max && ( $nmatches >= $max ) && !$after; + } + next; + } # not a match + + ++$nmatches; + + # print an empty line as a divider before first line in each file (not before the first file) + if ( !$any_output && $opt->{show_filename} && $opt->{break} && defined( $context_overall_output_count ) ) { + App::Ack::print_blank_line(); + } + + shift @lines if $has_lines; + + if ( $res->is_binary ) { + App::Ack::print( "Binary file $filename matches\n" ); + last; + } + if ( $keep_context ) { + if ( @before ) { + print_match_or_context( $opt, 0, $before_starts_at_line, $-[0], $+[0], @before ); + @before = (); + $before_starts_at_line = 0; + } + if ( $max && $nmatches > $max ) { + --$after; + } + else { + $after = $after_context; + } + } + print_match_or_context( $opt, 1, $., $-[0], $+[0], $_ ); + + last if $max && ( $nmatches >= $max ) && !$after; + } # while + + return $nmatches; +} # search_resource() + + + +sub print_match_or_context { + my $opt = shift; # opts array + my $is_match = shift; # is there a match on the line? + my $line_no = shift; + my $match_start = shift; + my $match_end = shift; + + my $color = $opt->{color}; + my $heading = $opt->{heading}; + my $show_filename = $opt->{show_filename}; + my $show_column = $opt->{column}; + + if ( $show_filename ) { + if ( not defined $display_filename ) { + $display_filename = + $color + ? Term::ANSIColor::colored( $filename, $ENV{ACK_COLOR_FILENAME} ) + : $filename; + if ( $heading && !$any_output ) { + App::Ack::print_first_filename($display_filename); + } + } + } + + my $sep = $is_match ? ':' : '-'; + my $output_func = $opt->{output}; + for ( @_ ) { + if ( $keep_context && !$output_func ) { + if ( ( $last_output_line != $line_no - 1 ) && + ( $any_output || ( !$heading && defined( $context_overall_output_count ) ) ) ) { + App::Ack::print_separator(); + } + # to ensure separators between different files when --noheading + + $last_output_line = $line_no; + } + + if ( $show_filename ) { + App::Ack::print_filename($display_filename, $sep) if not $heading; + App::Ack::print_line_no($line_no, $sep); + } + + if ( $output_func ) { + while ( /$regex/go ) { + App::Ack::print( $output_func->() . "\n" ); + } + } + else { + if ( $color && $is_match && $regex && + s/$regex/Term::ANSIColor::colored( substr($_, $-[0], $+[0] - $-[0]), $ENV{ACK_COLOR_MATCH} )/eg ) { + # At the end of the line reset the color and remove newline + s/[\r\n]*\z/\e[0m\e[K/; + } + else { + # remove any kind of newline at the end of the line + s/[\r\n]*\z//; + } + if ( $show_column ) { + App::Ack::print_column_no( $match_start+1, $sep ); + } + App::Ack::print($_ . "\n"); + } + $any_output = 1; + ++$context_overall_output_count; + ++$line_no; + } + + return; +} # print_match_or_context() + +} # scope around search_resource() and print_match_or_context() + + + +sub search_and_list { + my $res = shift; + my $opt = shift; + + my $nmatches = 0; + my $count = $opt->{count}; + my $ors = $opt->{print0} ? "\0" : "\n"; # output record separator + + my $regex = qr/$opt->{regex}/; + + if ( $opt->{v} ) { + while ( $res->next_text ) { + if ( /$regex/ ) { + return 0 unless $count; + } + else { + ++$nmatches; + } + } + } + else { + while ( $res->next_text ) { + if ( /$regex/ ) { + ++$nmatches; + last unless $count; + } + } + } + + if ( $nmatches ) { + App::Ack::print_count( $res->name, $nmatches, $ors, $count ); + } + elsif ( $count && !$opt->{l} ) { + App::Ack::print_count0( $res->name, $ors ); + } + + return $nmatches ? 1 : 0; +} # search_and_list() + + + +sub filetypes_supported_set { + return grep { defined $type_wanted{$_} && ($type_wanted{$_} == 1) } filetypes_supported(); +} + + + +sub print_files { + my $iter = shift; + my $opt = shift; + + my $ors = $opt->{print0} ? "\0" : "\n"; + + my $nmatches = 0; + while ( defined ( my $file = $iter->() ) ) { + App::Ack::print $file, $ors; + $nmatches++; + last if $opt->{1}; + } + + return $nmatches; +} + + +sub print_files_with_matches { + my $iter = shift; + my $opt = shift; + + my $nmatches = 0; + while ( defined ( my $filename = $iter->() ) ) { + my $repo = App::Ack::Repository::Basic->new( $filename ); + my $res; + while ( $res = $repo->next_resource() ) { + $nmatches += search_and_list( $res, $opt ); + $res->close(); + last if $nmatches && $opt->{1}; + } + $repo->close(); + } + + return $nmatches; +} + + +sub print_matches { + my $iter = shift; + my $opt = shift; + + $opt->{show_filename} = 0 if $opt->{h}; + $opt->{show_filename} = 1 if $opt->{H}; + + my $nmatches = 0; + while ( defined ( my $filename = $iter->() ) ) { + my $repo; + my $tarballs_work = 0; + if ( $tarballs_work && $filename =~ /\.tar\.gz$/ ) { + App::Ack::die( 'Not working here yet' ); + require App::Ack::Repository::Tar; # XXX Error checking + $repo = App::Ack::Repository::Tar->new( $filename ); + } + else { + $repo = App::Ack::Repository::Basic->new( $filename ); + } + $repo or next; + + while ( my $res = $repo->next_resource() ) { + my $needs_line_scan; + if ( $opt->{regex} && !$opt->{passthru} ) { + $needs_line_scan = $res->needs_line_scan( $opt ); + if ( $needs_line_scan ) { + $res->reset(); + } + } + else { + $needs_line_scan = 1; + } + if ( $needs_line_scan ) { + $nmatches += search_resource( $res, $opt ); + } + $res->close(); + } + last if $nmatches && $opt->{1}; + $repo->close(); + } + return $nmatches; +} + + +sub filetype_setup { + my $filetypes_supported_set = filetypes_supported_set(); + # If anyone says --no-whatever, we assume all other types must be on. + if ( !$filetypes_supported_set ) { + for my $i ( keys %type_wanted ) { + $type_wanted{$i} = 1 unless ( defined( $type_wanted{$i} ) || $i eq 'binary' || $i eq 'text' || $i eq 'skipped' ); + } + } + return; +} + + +EXPAND_FILENAMES_SCOPE: { + my $filter; + + sub expand_filenames { + my $argv = shift; + + my $attr; + my @files; + + foreach my $pattern ( @{$argv} ) { + my @results = bsd_glob( $pattern ); + + if (@results == 0) { + @results = $pattern; # Glob didn't match, pass it thru unchanged + } + elsif ( (@results > 1) or ($results[0] ne $pattern) ) { + if (not defined $filter) { + eval 'require Win32::File;'; + if ($@) { + $filter = 0; + } + else { + $filter = Win32::File::HIDDEN()|Win32::File::SYSTEM(); + } + } # end unless we've tried to load Win32::File + if ( $filter ) { + # Filter out hidden and system files: + @results = grep { not(Win32::File::GetAttributes($_, $attr) and $attr & $filter) } @results; + App::Ack::warn( "$pattern: Matched only hidden files" ) unless @results; + } # end if we can filter by file attributes + } # end elsif this pattern got expanded + + push @files, @results; + } # end foreach pattern + + return \@files; + } # end expand_filenames +} # EXPAND_FILENAMES_SCOPE + + + +sub get_starting_points { + my $argv = shift; + my $opt = shift; + + my @what; + + if ( @{$argv} ) { + @what = @{ $is_windows ? expand_filenames($argv) : $argv }; + $_ = File::Next::reslash( $_ ) for @what; + + # Show filenames unless we've specified one single file + $opt->{show_filename} = (@what > 1) || (!-f $what[0]); + } + else { + @what = '.'; # Assume current directory + $opt->{show_filename} = 1; + } + + for my $start_point (@what) { + App::Ack::warn( "$start_point: No such file or directory" ) unless -e $start_point; + } + return \@what; +} + + + +sub get_iterator { + my $what = shift; + my $opt = shift; + + # Starting points are always searched, no matter what + my %starting_point = map { ($_ => 1) } @{$what}; + + my $g_regex = defined $opt->{G} ? qr/$opt->{G}/ : undef; + my $file_filter; + + if ( $g_regex ) { + $file_filter + = $opt->{u} ? sub { $File::Next::name =~ /$g_regex/ } # XXX Maybe this should be a 1, no? + : $opt->{all} ? sub { $starting_point{ $File::Next::name } || ( $File::Next::name =~ /$g_regex/ && is_searchable( $_ ) ) } + : sub { $starting_point{ $File::Next::name } || ( $File::Next::name =~ /$g_regex/ && is_interesting( @_ ) ) } + ; + } + else { + $file_filter + = $opt->{u} ? sub {1} + : $opt->{all} ? sub { $starting_point{ $File::Next::name } || is_searchable( $_ ) } + : sub { $starting_point{ $File::Next::name } || is_interesting( @_ ) } + ; + } + + my $descend_filter + = $opt->{n} ? sub {0} + : $opt->{u} ? sub {1} + : \&ignoredir_filter; + + my $iter = + File::Next::files( { + file_filter => $file_filter, + descend_filter => $descend_filter, + error_handler => sub { my $msg = shift; App::Ack::warn( $msg ) }, + sort_files => $opt->{sort_files}, + follow_symlinks => $opt->{follow}, + }, @{$what} ); + return $iter; +} + + +sub set_up_pager { + my $command = shift; + + return if App::Ack::output_to_pipe(); + + my $pager; + if ( not open( $pager, '|-', $command ) ) { + App::Ack::die( qq{Unable to pipe to pager "$command": $!} ); + } + $fh = $pager; + + return; +} + + +sub input_from_pipe { + return $input_from_pipe; +} + + + +sub output_to_pipe { + return $output_to_pipe; +} + + + +1; # End of App::Ack +package App::Ack::Repository; + + +use warnings; +use strict; + +sub FAIL { + require Carp; + Carp::confess( 'Must be overloaded' ); +} + + +sub new { + FAIL(); +} + + +sub next_resource { + FAIL(); +} + + +sub close { + FAIL(); +} + +1; +package App::Ack::Resource; + + +use warnings; +use strict; + +sub FAIL { + require Carp; + Carp::confess( 'Must be overloaded' ); +} + + +sub new { + FAIL(); +} + + +sub name { + FAIL(); +} + + +sub is_binary { + FAIL(); +} + + + +sub needs_line_scan { + FAIL(); +} + + +sub reset { + FAIL(); +} + + +sub next_text { + FAIL(); +} + + +sub close { + FAIL(); +} + +1; +package App::Ack::Plugin::Basic; + + + +package App::Ack::Resource::Basic; + + +use warnings; +use strict; + + +our @ISA = qw( App::Ack::Resource ); + + +sub new { + my $class = shift; + my $filename = shift; + + my $self = bless { + filename => $filename, + fh => undef, + could_be_binary => undef, + opened => undef, + id => undef, + }, $class; + + if ( $self->{filename} eq '-' ) { + $self->{fh} = *STDIN; + $self->{could_be_binary} = 0; + } + else { + if ( !open( $self->{fh}, '<', $self->{filename} ) ) { + App::Ack::warn( "$self->{filename}: $!" ); + return; + } + $self->{could_be_binary} = 1; + } + + return $self; +} + + +sub name { + my $self = shift; + + return $self->{filename}; +} + + +sub is_binary { + my $self = shift; + + if ( $self->{could_be_binary} ) { + return -B $self->{filename}; + } + + return 0; +} + + + +sub needs_line_scan { + my $self = shift; + my $opt = shift; + + return 1 if $opt->{v}; + + my $size = -s $self->{fh}; + if ( $size == 0 ) { + return 0; + } + elsif ( $size > 100_000 ) { + return 1; + } + + my $buffer; + my $rc = sysread( $self->{fh}, $buffer, $size ); + if ( not defined $rc ) { + App::Ack::warn( "$self->{filename}: $!" ); + return 1; + } + return 0 unless $rc && ( $rc == $size ); + + my $regex = $opt->{regex}; + return $buffer =~ /$regex/m; +} + + +sub reset { + my $self = shift; + + seek( $self->{fh}, 0, 0 ) + or App::Ack::warn( "$self->{filename}: $!" ); + + return; +} + + +sub next_text { + if ( defined ($_ = readline $_[0]->{fh}) ) { + $. = ++$_[0]->{line}; + return 1; + } + + return; +} + + +sub close { + my $self = shift; + + if ( not close $self->{fh} ) { + App::Ack::warn( $self->name() . ": $!" ); + } + + return; +} + +package App::Ack::Repository::Basic; + + +our @ISA = qw( App::Ack::Repository ); + + +use warnings; +use strict; + +sub new { + my $class = shift; + my $filename = shift; + + my $self = bless { + filename => $filename, + nexted => 0, + }, $class; + + return $self; +} + + +sub next_resource { + my $self = shift; + + return if $self->{nexted}; + $self->{nexted} = 1; + + return App::Ack::Resource::Basic->new( $self->{filename} ); +} + + +sub close { +} + + + +1; diff --git a/svn-authorsfile b/svn-authorsfile new file mode 100755 index 0000000..5d1a618 --- /dev/null +++ b/svn-authorsfile @@ -0,0 +1,6 @@ +#!/usr/bin/bash + +authors=$(svn log -q | grep -e '^r' | awk 'BEGIN { FS = "|" } ; { print $2 }' | sort | uniq) +for author in ${authors}; do + echo "${author} = NAME <USER@DOMAIN>"; +done
anarchivist/tildebin
57978018bb2c83f3df4ae29c26c89f5e1b7d8711
Fix fits to actually allow passing of arguments
diff --git a/fits b/fits index f9d2cfb..1b2f323 100755 --- a/fits +++ b/fits @@ -1,3 +1,3 @@ #!/bin/bash export FITS_DIR=/opt/fits-0.3.2 -exec $FITS_DIR/fits.sh \ No newline at end of file +exec $FITS_DIR/fits.sh "$@"
anarchivist/tildebin
6e6a6d66303cddb38cf6e0be4e1785d7f75ae151
add fits
diff --git a/README.textile b/README.textile index aed10fd..f120055 100644 --- a/README.textile +++ b/README.textile @@ -1,12 +1,11 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. - -h2. Who to blame -* "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist +* Blame "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist h2. Possibly incomplete list of scripts and what they do +* fits: Launch "FITS, the file information toolset":http://code.google.com/p/fits/ * mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image * osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. \ No newline at end of file diff --git a/fits b/fits new file mode 100755 index 0000000..f9d2cfb --- /dev/null +++ b/fits @@ -0,0 +1,3 @@ +#!/bin/bash +export FITS_DIR=/opt/fits-0.3.2 +exec $FITS_DIR/fits.sh \ No newline at end of file
anarchivist/tildebin
1403ed4ed55e648a9b54efbe517cb61ffa458c93
Add more comments etc
diff --git a/README.textile b/README.textile index e49218f..aed10fd 100644 --- a/README.textile +++ b/README.textile @@ -1,8 +1,12 @@ h1. README * These are scripts of use to me that may be of marginal use to you. * They are likely environment specific; fwiw, I'm running these either on Mac OS X 10.6 or Ubuntu. +h2. Who to blame +* "Mark A. Matienzo, aka anarchivist":http://github.com/anarchivist + h2. Possibly incomplete list of scripts and what they do -* mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image \ No newline at end of file +* mount-fedora-image: Mounts a copy of Mediashelf's "FedoraSolr Mac OS X DMG":http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image +* osx-force-path-to-prefs: Copies value of $PATH to a preferences file for use by Finder, Textmate, etc. \ No newline at end of file diff --git a/mount-fedora-image b/mount-fedora-image index a237744..8413762 100755 --- a/mount-fedora-image +++ b/mount-fedora-image @@ -1,6 +1,10 @@ #!/bin/bash +# +# Mounts Fedora/Solr disk image, downloadable from the following URL: +# http://projects.mediashelf.us/wiki/active-fedora/Blank_FedoraSolr_Disk_Image + export FEDORA_IMAGE_DIR=$HOME/Documents/Yale/fedora-testing-image export FEDORA_IMAGE_NAME=$FEDORA_IMAGE_DIR/fedora-3.2.1-solr-1.3.0-testing.dmg export FEDORA_HOME=/Volumes/fedora-solr-testing/fedora export CATLINA_HOME=$FEDORA_HOME/tomcat hdiutil attach $FEDORA_IMAGE_NAME -shadow $FEDORA_IMAGE_NAME.shadow diff --git a/osx-force-path-to-prefs b/osx-force-path-to-prefs index a2f4f44..23e0b86 100755 --- a/osx-force-path-to-prefs +++ b/osx-force-path-to-prefs @@ -1,3 +1,4 @@ #!/bin/bash +# Force value of PATH to a pref file for use by textmate and other apps defaults write $HOME/.MacOSX/environment "PATH" "$PATH" plutil -convert xml1 $HOME/.MacOSX/environment.plist \ No newline at end of file
darka/blahnet
8fdc83820326e06249c664852bc8648035046d36
handle self assignment; packet header changes
diff --git a/src/address.cpp b/src/address.cpp index 49cdf38..4279821 100644 --- a/src/address.cpp +++ b/src/address.cpp @@ -1,70 +1,71 @@ #include "address.hpp" #ifdef BLAHNET_WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <arpa/inet.h> #endif // BLAHNET_WIN32 #include <cstring> void zero_pad_data(sockaddr_in& data) { std::memset(data.sin_zero, '\0', sizeof(data.sin_zero)); } void copy_data(sockaddr_in const& from, sockaddr_in& to) { to.sin_family = from.sin_family; to.sin_port = from.sin_port; to.sin_addr.s_addr = from.sin_addr.s_addr; zero_pad_data(to); } address::address() : data_(new sockaddr_in) { } address::address(unsigned short int port) : data_(new sockaddr_in) { data_->sin_family = AF_INET; data_->sin_port = htons(port); data_->sin_addr.s_addr = INADDR_ANY; zero_pad_data(*data_); } address::address(unsigned short int port, char const* ip) : data_(new sockaddr_in) { data_->sin_family = AF_INET; data_->sin_port = htons(port); data_->sin_addr.s_addr = inet_addr(ip); zero_pad_data(*data_); } address::address(address const& other) : data_(new sockaddr_in) { copy_data(*other.data_, *this->data_); } address::~address() { clear(); } address& address::operator=(address const& other) { + if (this == &other) return *this; clear(); data_ = new sockaddr_in(); copy_data(*other.data_, *this->data_); return *this; } void address::clear() { delete data_; } diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index 8088ef5..a3acd13 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,263 +1,264 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(false) { buffer = new buffer_type[size_]; memset(buffer, 0, size_); } bit_stream::bit_stream(bit_stream const& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) , allocated_externally(false) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(true) { } bit_stream::~bit_stream() { clear(); } bit_stream& bit_stream::operator=(bit_stream const& other) { + if (this == &other) return *this; clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); allocated_externally = false; return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } //std::cout << new_size << "\n"; resize(new_size); } void bit_stream::resize(std::size_t new_size) { assert(new_size >= size_); if (new_size == size_) return; buffer_type* new_buffer = new buffer_type[new_size]; // set everything that's not to be overwritten on the new // buffer to 0 memset(new_buffer + size_, 0, new_size - size_); memcpy(new_buffer, buffer, size_); if (allocated_externally == false) delete[] buffer; allocated_externally = false; buffer = new_buffer; size_ = new_size; } void bit_stream::write_bool(bool n) { write_bit(n); } void bit_stream::write_uint(uint32 n, unsigned int bits) { if (bits > 32) throw bit_stream_error("cannot write more than 32 bits"); else if (bits == 0) return; affirm_size(bits); unsigned int i = 0; // How many bits we've already written while (i < bits) { unsigned int bits_to_write; // How many bits we'll be writing // There are 2 possibilities, either we're writing until the end of the byte on the buffer // or we aren't! We have to make the choice from either if ((8 - cur_rel_bit) <= (bits - i)) { // We get here if we're writing to the end of the current byte // on the buffer bits_to_write = 8 - cur_rel_bit; buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); ++cur_byte; } else { // We get here if writing all the bits we're still left to write // won't make us reach the end of the byte we're writing to bits_to_write = bits - i; uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); portion >>= cur_rel_bit; buffer[cur_byte] |= portion; } i += bits_to_write; cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; } } bool bit_stream::read_bool() { return read_bit(); } void bit_stream::write_sint(sint32 n, unsigned int bits) { write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { assert(bits <= 32); uint32 ret = 0; unsigned int i = 0; while (i < bits) { unsigned int bits_to_write; if ((bits - i) <= (8 - cur_rel_bit)) { // We're here because on the current byte in the buffer we have // bits to the right that we're supposed to skip bits_to_write = bits - i; uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; assert(bits_to_write <= 8); ret |= (portion >> (8 - bits_to_write)); } else { // We're here to read the current byte on the buffer from // cur_rel_bit till the end bits_to_write = 8 - cur_rel_bit; // Clear up the leftmost bits uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; portion >>= cur_rel_bit; assert(bits - i - bits_to_write <= bits); ret |= (portion << (bits - i - bits_to_write)); } i += bits_to_write; cur_rel_bit = cur_rel_bit + bits_to_write; if (cur_rel_bit >= 8) { ++cur_byte; cur_rel_bit %= 8; } } return ret; } sint32 bit_stream::read_sint(unsigned int bits) { return static_cast<sint32>(read_uint(bits)); } void bit_stream::write_string(std::string const& str) { write_uint(str.size(), 32); for (std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) { write_uint(*iter, 8); } } std::string bit_stream::read_string() { std::string ret; std::string::size_type chars = read_uint(32); for (std::string::size_type i = 0; i < chars; ++i) { ret.append(1, read_uint(8)); } return ret; } void bit_stream::append(bit_stream const& bs) { affirm_size(bs.cur_byte * 8 + bs.cur_rel_bit); if (cur_rel_bit == 0) { memcpy(buffer + cur_byte, bs.buffer, bs.cur_byte + (bs.cur_rel_bit > 0)); cur_byte += bs.cur_byte; cur_rel_bit = bs.cur_rel_bit; } else { for (std::size_t i = 0; i < bs.cur_byte + (bs.cur_rel_bit > 0); ++i) { write_uint(bs.buffer[i], 8); } } } #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { if (buffer != 0 && allocated_externally == false) delete[] buffer; } void bit_stream::write_bit(bool bit) { affirm_size(1); buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); inc_bit(); } bool bit_stream::read_bit() { bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; inc_bit(); return ret; } void bit_stream::inc_bit() { cur_rel_bit += 1; if (cur_rel_bit == 8) { cur_byte += 1; cur_rel_bit = 0; } } diff --git a/src/link_common.cpp b/src/link_common.cpp index f0bd776..80bbb72 100644 --- a/src/link_common.cpp +++ b/src/link_common.cpp @@ -1,25 +1,24 @@ #include "link_common.hpp" // TODO: error handling with exceptions link_common::link_common() { } -bit_stream link_common::add_header(bit_stream const& msg, uint8 peer_id, +bit_stream link_common::add_header(bit_stream const& msg, message_type msg_type, bool is_ack) { bit_stream packet(header_size); - packet.write_uint(protocol_version); - packet.write_uint(peer_id); - packet.write_uint(msg_type); - packet.write_uint(is_ack); // not an ack packet + packet.write_uint(protocol_version, 4); + packet.write_uint(msg_type, 3); + packet.write_bool(is_ack); packet.append(msg); return packet; } link_common::~link_common() { sock.close(); } diff --git a/src/link_common.hpp b/src/link_common.hpp index 98fc9c2..dcc5b05 100644 --- a/src/link_common.hpp +++ b/src/link_common.hpp @@ -1,50 +1,49 @@ #ifndef UUID_52DA523EF9CE4CF3A46629AAEC07E467 #define UUID_52DA523EF9CE4CF3A46629AAEC07E467 #include "bit_stream.hpp" #include "udp_socket.hpp" #include <boost/signal.hpp> #include <queue> struct link_common { enum disconnection_reason { timeout = 0, voluntary = 1 }; enum message_type { reliable_ordered = 0 /* unreliable_ordered = 1, reliable_unordered = 2, unreliable_unordered = 3, */ }; ~link_common(); //void host(unsigned short int port); //void connect(address const& addr); //void send(bit_stream const& data); - static uint8 const header_size = 2; // in bytes + static uint8 const header_size = 1; // in bytes static uint8 const protocol_version = 0; // Header: // 4 bits: protocol id - // 8 bits: unique peer id <- we don't need this apparently // 3 bits: message type // 1 bit : is an ack packet protected: link_common(); - bit_stream add_header(bit_stream const& msg, uint8 peer_id, + bit_stream add_header(bit_stream const& msg, message_type msg_type, bool is_ack); //bool connected; //address addr; udp_socket sock; //std::queue<packet*> packets; }; #endif // UUID_52DA523EF9CE4CF3A46629AAEC07E467 diff --git a/src/server.cpp b/src/server.cpp index 228472e..c1e4e03 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1,101 +1,87 @@ #include "server.hpp" -#include "bit_stream.hpp" +#include "bit_stream.hpp" server::server() : expecting(false) { } void server::host(unsigned short int port) { sock.create(); sock.bind(port); } void server::work() { // receive packets - // TODO: enforce default max packet size everywhere? + // TODO: enforce default max packet size everywhere? // should go into link_common if so // If anything we need to check the size isn't too small unsigned int const packet_size = 20; char raw_msg[packet_size]; address addr; int result = sock.recvfrom(raw_msg, packet_size - 1, addr); bit_stream msg(reinterpret_cast<uint8*>(raw_msg), packet_size); if (result != -1) { // TODO: should disconnect the client instead assert((msg.read_uint(4)) == protocol_version); // TODO: check if such peer exists at all peer* sender = peers[msg.read_uint(8)]; uint8 msg_type = msg.read_uint(3); // is packet an ack? if (msg.read_uint(1)) { uint8 seq_number = msg.read_uint(8); //if (expecting && seq_number == sender->outgoing_seq_number()) // pop_top_packet(); } else { // send an ack // TODO: pack many acks in one packet } } - + /*if (packets.empty()) { expecting = false; } else { // send top packet packet* current_packet = packets.front(); // TODO: error checking sock.sendto(current_packet->msg, current_packet->msg_len, current_packet->addr); expecting = true; expected_num = current_packet->msg[1]; pop_top_packet(); }*/ } void server::stop() { sock.close(); } -void server::sendto(char* msg, std::size_t msg_len, - uint8 peer_id) +void server::send(bit_stream const& msg, message_type msg_type, + address const& addr) { // TODO: split the packet here? need to guard against overflow anyway - /*std::size_t prepared_msg_len = msg_len + 2; - char* prepared_msg = new char[prepared_msg_len]; - std::memcpy(prepared_msg + 2, msg, msg_len); - std::memset(prepared_msg, 0, 2); - - // attach header - // first 7 bits = protocol version - // TODO: (how else do we do this? on connection? look at q3 - prepared_msg[0] |= (protocol_version << 1); - // we're not sending an ack packet, so the 8th bit is 1 - prepared_msg[0] |= 1; - // attach sequence number - prepared_msg[1] |= seq_num;*/ - bit_stream bs(reinterpret_cast<bit_stream::buffer_type*>(msg), msg_len); - bit_stream packet(header_size); - packet.write_uint(protocol_version); - packet.write_uint(peer_id); - packet.write_uint(reliable_ordered); - packet.write_uint(false); // not an ack packet - packet.append(bs); // store in a queue? //packets.push(packet); - counters[reliable_ordered] += 1; + switch (msg_type) + { + default: + counters[msg_type] += 1; + break; + } + } diff --git a/src/server.hpp b/src/server.hpp index 09e7c35..bd6ab22 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -1,34 +1,34 @@ #ifndef UUID_A3C8588901A048B6B6FB438C5F31BBCF #define UUID_A3C8588901A048B6B6FB438C5F31BBCF #include "link_common.hpp" #include "peer.hpp" #include <map> struct server : public link_common { server(); void host(unsigned short int port); void work(); void stop(); // does nothing if not hosting - void sendto(char* msg, std::size_t msg_len, - uint8 peer_id); + void send(bit_stream const& msg, message_type msg_type, + address const& addr); // TODO: how to cache the addresses? ??? boost::signal<void (address const&)> on_connect; boost::signal<void (address const&, disconnection_reason const&)> on_disconnect; boost::signal<void (address const&, bit_stream const&)> on_receive; private: void generateId(); std::map<uint8, peer*> peers; // unique peer id => peer bool expecting; uint8 id; std::map<message_type, uint8> counters; }; #endif // UUID_A3C8588901A048B6B6FB438C5F31BBCF diff --git a/src/types.hpp b/src/types.hpp index 742f757..e13743a 100644 --- a/src/types.hpp +++ b/src/types.hpp @@ -1,10 +1,11 @@ #ifndef UUID_2AA4C0A26AE64469A744D08C77A457CD #define UUID_2AA4C0A26AE64469A744D08C77A457CD +// TODO: use boost cstdint types instead? typedef unsigned int uint32; typedef unsigned char uint8; typedef int sint32; typedef signed char sint8; #endif // UUID_2AA4C0A26AE64469A744D08C77A457CD
darka/blahnet
9d6bd3c00d7f1063821f3269983bfde6bc7dd9f1
address op= and copy constructor + unit test; bit_stream_error exception; untested add_header function; more work on client/server classes
diff --git a/src/address.cpp b/src/address.cpp index e287c3e..49cdf38 100644 --- a/src/address.cpp +++ b/src/address.cpp @@ -1,44 +1,70 @@ #include "address.hpp" #ifdef BLAHNET_WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <arpa/inet.h> #endif // BLAHNET_WIN32 #include <cstring> -void zero_pad(sockaddr_in& data) +void zero_pad_data(sockaddr_in& data) { std::memset(data.sin_zero, '\0', sizeof(data.sin_zero)); } +void copy_data(sockaddr_in const& from, sockaddr_in& to) +{ + to.sin_family = from.sin_family; + to.sin_port = from.sin_port; + to.sin_addr.s_addr = from.sin_addr.s_addr; + zero_pad_data(to); +} + address::address() : data_(new sockaddr_in) { } address::address(unsigned short int port) : data_(new sockaddr_in) { data_->sin_family = AF_INET; data_->sin_port = htons(port); data_->sin_addr.s_addr = INADDR_ANY; - zero_pad(*data_); + zero_pad_data(*data_); } address::address(unsigned short int port, char const* ip) : data_(new sockaddr_in) { data_->sin_family = AF_INET; data_->sin_port = htons(port); data_->sin_addr.s_addr = inet_addr(ip); - zero_pad(*data_); + zero_pad_data(*data_); +} + +address::address(address const& other) +: data_(new sockaddr_in) +{ + copy_data(*other.data_, *this->data_); } address::~address() { - delete data_; + clear(); +} + +address& address::operator=(address const& other) +{ + clear(); + data_ = new sockaddr_in(); + copy_data(*other.data_, *this->data_); + return *this; } +void address::clear() +{ + delete data_; +} diff --git a/src/address.hpp b/src/address.hpp index c889924..2b38610 100644 --- a/src/address.hpp +++ b/src/address.hpp @@ -1,28 +1,28 @@ #ifndef UUID_8B00007D6BED43B1AF63C689D9D35D78 #define UUID_8B00007D6BED43B1AF63C689D9D35D78 struct sockaddr_in; -/* TODO: implement copy constructor and operator= */ struct address { address(); /* uses host's ip address and picks a port automatically */ - address(unsigned short int port); /* uses host's ip address and + address(unsigned short int port); /* uses host's ip address and uses given port */ - address(unsigned short int port, char const* ip); /* uses given ip + address(unsigned short int port, char const* ip); /* uses given ip and port */ address(address const& other); ~address(); address& operator=(address const& other); /*unsigned short int port() const; const char* ip() const;*/ - sockaddr_in const* data() const { return data_; } - sockaddr_in* data() { return data_; } - + sockaddr_in const* data() const { return data_; } + sockaddr_in* data() { return data_; } + private: + void clear(); sockaddr_in* data_; }; #endif // UUID_8B00007D6BED43B1AF63C689D9D35D78 diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index a9e9376..8088ef5 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,257 +1,263 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(false) { buffer = new buffer_type[size_]; memset(buffer, 0, size_); } bit_stream::bit_stream(bit_stream const& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) , allocated_externally(false) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(true) { } bit_stream::~bit_stream() { clear(); } bit_stream& bit_stream::operator=(bit_stream const& other) { clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); allocated_externally = false; return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } //std::cout << new_size << "\n"; resize(new_size); } void bit_stream::resize(std::size_t new_size) { assert(new_size >= size_); if (new_size == size_) return; buffer_type* new_buffer = new buffer_type[new_size]; - // TODO: some redundancy here - memset(new_buffer, 0, new_size); + + // set everything that's not to be overwritten on the new + // buffer to 0 + memset(new_buffer + size_, 0, new_size - size_); memcpy(new_buffer, buffer, size_); + if (allocated_externally == false) delete[] buffer; allocated_externally = false; buffer = new_buffer; size_ = new_size; } void bit_stream::write_bool(bool n) { write_bit(n); } void bit_stream::write_uint(uint32 n, unsigned int bits) { - // TODO: throw if bits > 32 - assert(bits <= 32); + if (bits > 32) + throw bit_stream_error("cannot write more than 32 bits"); + else if (bits == 0) + return; + affirm_size(bits); unsigned int i = 0; // How many bits we've already written while (i < bits) { unsigned int bits_to_write; // How many bits we'll be writing // There are 2 possibilities, either we're writing until the end of the byte on the buffer // or we aren't! We have to make the choice from either if ((8 - cur_rel_bit) <= (bits - i)) { // We get here if we're writing to the end of the current byte // on the buffer bits_to_write = 8 - cur_rel_bit; buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); ++cur_byte; } else { // We get here if writing all the bits we're still left to write // won't make us reach the end of the byte we're writing to bits_to_write = bits - i; uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); portion >>= cur_rel_bit; buffer[cur_byte] |= portion; } i += bits_to_write; cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; } } bool bit_stream::read_bool() { return read_bit(); } void bit_stream::write_sint(sint32 n, unsigned int bits) { write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { assert(bits <= 32); uint32 ret = 0; unsigned int i = 0; while (i < bits) { unsigned int bits_to_write; if ((bits - i) <= (8 - cur_rel_bit)) { // We're here because on the current byte in the buffer we have // bits to the right that we're supposed to skip bits_to_write = bits - i; uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; - + assert(bits_to_write <= 8); ret |= (portion >> (8 - bits_to_write)); } else { // We're here to read the current byte on the buffer from // cur_rel_bit till the end bits_to_write = 8 - cur_rel_bit; - + // Clear up the leftmost bits uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; portion >>= cur_rel_bit; - + assert(bits - i - bits_to_write <= bits); ret |= (portion << (bits - i - bits_to_write)); } i += bits_to_write; cur_rel_bit = cur_rel_bit + bits_to_write; if (cur_rel_bit >= 8) { ++cur_byte; cur_rel_bit %= 8; } } return ret; } sint32 bit_stream::read_sint(unsigned int bits) { return static_cast<sint32>(read_uint(bits)); } void bit_stream::write_string(std::string const& str) { write_uint(str.size(), 32); for (std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) { write_uint(*iter, 8); } } std::string bit_stream::read_string() { std::string ret; std::string::size_type chars = read_uint(32); for (std::string::size_type i = 0; i < chars; ++i) { ret.append(1, read_uint(8)); } - return ret; + return ret; } void bit_stream::append(bit_stream const& bs) { affirm_size(bs.cur_byte * 8 + bs.cur_rel_bit); if (cur_rel_bit == 0) { memcpy(buffer + cur_byte, bs.buffer, bs.cur_byte + (bs.cur_rel_bit > 0)); cur_byte += bs.cur_byte; cur_rel_bit = bs.cur_rel_bit; } else { for (std::size_t i = 0; i < bs.cur_byte + (bs.cur_rel_bit > 0); ++i) { write_uint(bs.buffer[i], 8); } } } #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { if (buffer != 0 && allocated_externally == false) delete[] buffer; } void bit_stream::write_bit(bool bit) { affirm_size(1); buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); inc_bit(); } bool bit_stream::read_bit() { bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; - inc_bit(); + inc_bit(); return ret; } void bit_stream::inc_bit() { cur_rel_bit += 1; if (cur_rel_bit == 8) { cur_byte += 1; cur_rel_bit = 0; } } diff --git a/src/bit_stream.hpp b/src/bit_stream.hpp index 67bf142..107d283 100644 --- a/src/bit_stream.hpp +++ b/src/bit_stream.hpp @@ -1,63 +1,71 @@ #ifndef UUID_3A39D07169584AA1A5A6E890BF40AEC4 #define UUID_3A39D07169584AA1A5A6E890BF40AEC4 #include "types.hpp" #include <cstddef> #include <string> #include <stdexcept> // TODO: perhaps split class into read and write bit_streams +struct bit_stream_error : public std::logic_error +{ + bit_stream_error(std::string const& message) + : std::logic_error(message) + { + } +}; struct bit_stream { typedef uint8 buffer_type; bit_stream(std::size_t size=4); bit_stream(bit_stream const& other); bit_stream(buffer_type* data, std::size_t size); ~bit_stream(); bit_stream& operator=(bit_stream const& other); void write_bool(bool n); bool read_bool(); void write_uint(uint32 n, unsigned int bits=32); uint32 read_uint(unsigned int bits=32); void write_sint(sint32 n, unsigned int bits=32); sint32 read_sint(unsigned int bits=32); void write_string(std::string const& str); std::string read_string(); void append(bit_stream const& bs); buffer_type const* raw_data() const { return buffer; } buffer_type* raw_data() { return buffer; } std::size_t size() const { return size_; } + // TODO: this should be debug only, along with seek(...) #if 0 void printContents() const; #endif void seek(unsigned int bit); private: void write_bit(bool bit); bool read_bit(); void inc_bit(); // increments cur_rel_bit and cur_byte if needed void affirm_size(std::size_t bits); void resize(std::size_t new_size); void clear(); buffer_type* buffer; std::size_t size_; std::size_t cur_byte; // current byte unsigned int cur_rel_bit; // relative to current byte bool allocated_externally; }; #endif // UUID_3A39D07169584AA1A5A6E890BF40AEC4 diff --git a/src/client.cpp b/src/client.cpp new file mode 100644 index 0000000..9b520c6 --- /dev/null +++ b/src/client.cpp @@ -0,0 +1,15 @@ +#include "client.hpp" + +client::client() +{ +} + +client::~client() +{ +} + +void client::connect(address const& addr) +{ + sock.create(); + // TODO: send a packet informing of connection +} diff --git a/src/client.hpp b/src/client.hpp index 2c5fc23..44978b1 100644 --- a/src/client.hpp +++ b/src/client.hpp @@ -1,17 +1,18 @@ #ifndef UUID_D9717A39A7864EDC96BAA9C5A9A7E38C #define UUID_D9717A39A7864EDC96BAA9C5A9A7E38C +#include "address.hpp" +#include "link_common.hpp" -struct client +struct client : public link_common { client(); - + void connect(address const& addr); ~client(); private: - }; #endif // UUID_D9717A39A7864EDC96BAA9C5A9A7E38C diff --git a/src/link_common.cpp b/src/link_common.cpp index eb43bb0..f0bd776 100644 --- a/src/link_common.cpp +++ b/src/link_common.cpp @@ -1,13 +1,25 @@ #include "link_common.hpp" // TODO: error handling with exceptions link_common::link_common() { } +bit_stream link_common::add_header(bit_stream const& msg, uint8 peer_id, + message_type msg_type, bool is_ack) +{ + bit_stream packet(header_size); + packet.write_uint(protocol_version); + packet.write_uint(peer_id); + packet.write_uint(msg_type); + packet.write_uint(is_ack); // not an ack packet + packet.append(msg); + return packet; +} + link_common::~link_common() { sock.close(); } diff --git a/src/link_common.hpp b/src/link_common.hpp index 6db5f68..98fc9c2 100644 --- a/src/link_common.hpp +++ b/src/link_common.hpp @@ -1,48 +1,50 @@ #ifndef UUID_52DA523EF9CE4CF3A46629AAEC07E467 #define UUID_52DA523EF9CE4CF3A46629AAEC07E467 #include "bit_stream.hpp" #include "udp_socket.hpp" #include <boost/signal.hpp> #include <queue> struct link_common { enum disconnection_reason { timeout = 0, voluntary = 1 }; enum message_type { reliable_ordered = 0 /* unreliable_ordered = 1, reliable_unordered = 2, unreliable_unordered = 3, */ }; ~link_common(); - + //void host(unsigned short int port); //void connect(address const& addr); //void send(bit_stream const& data); - + static uint8 const header_size = 2; // in bytes static uint8 const protocol_version = 0; // Header: // 4 bits: protocol id - // 8 bits: unique peer id + // 8 bits: unique peer id <- we don't need this apparently // 3 bits: message type // 1 bit : is an ack packet protected: link_common(); + bit_stream add_header(bit_stream const& msg, uint8 peer_id, + message_type msg_type, bool is_ack); //bool connected; //address addr; udp_socket sock; //std::queue<packet*> packets; }; #endif // UUID_52DA523EF9CE4CF3A46629AAEC07E467 diff --git a/src/server.hpp b/src/server.hpp index b61308c..09e7c35 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -1,32 +1,34 @@ #ifndef UUID_A3C8588901A048B6B6FB438C5F31BBCF #define UUID_A3C8588901A048B6B6FB438C5F31BBCF #include "link_common.hpp" #include "peer.hpp" #include <map> struct server : public link_common { server(); void host(unsigned short int port); void work(); void stop(); // does nothing if not hosting void sendto(char* msg, std::size_t msg_len, uint8 peer_id); // TODO: how to cache the addresses? ??? boost::signal<void (address const&)> on_connect; - boost::signal<void (address const&, + boost::signal<void (address const&, disconnection_reason const&)> on_disconnect; - + boost::signal<void (address const&, bit_stream const&)> on_receive; private: + void generateId(); + std::map<uint8, peer*> peers; // unique peer id => peer - std::map<message_type, uint8> counters; bool expecting; - + uint8 id; + std::map<message_type, uint8> counters; }; #endif // UUID_A3C8588901A048B6B6FB438C5F31BBCF diff --git a/tests/address_test.cpp b/tests/address_test.cpp new file mode 100644 index 0000000..c7310a8 --- /dev/null +++ b/tests/address_test.cpp @@ -0,0 +1,36 @@ +#include "address.hpp" +#include <netinet/in.h> +#include <tut.h> + +namespace tut +{ + struct address_data + { + + }; + + typedef test_group<address_data> tg; + tg address_tg("address test"); + + template<> template<> + void tg::object::test<1>() + { + set_test_name("copy constructor and operator= test"); + address a(6666, "127.0.0.1"); + address b(a); + address c(7777, "0.0.0.0"); + c = a; + sockaddr_in* a_sock = a.data(); + sockaddr_in* b_sock = b.data(); + sockaddr_in* c_sock = c.data(); + ensure_equals("a and b sin_family", a_sock->sin_family, b_sock->sin_family); + ensure_equals("a and c sin_family", a_sock->sin_family, c_sock->sin_family); + ensure_equals("a and b sin_addr", a_sock->sin_addr.s_addr, b_sock->sin_addr.s_addr); + ensure_equals("a and c sin_addr", a_sock->sin_addr.s_addr, c_sock->sin_addr.s_addr); + ensure_equals("a and b sin_port", a_sock->sin_port, b_sock->sin_port); + ensure_equals("a and c sin_port", a_sock->sin_port, c_sock->sin_port); + b_sock->sin_port = htons(5555); + c_sock->sin_port = htons(4444); + ensure_equals("a sin_port after changes", a_sock->sin_port, htons(6666)); + } +} diff --git a/tests/bit_stream_test.cpp b/tests/bit_stream_test.cpp index 2e5c40b..bcedda1 100644 --- a/tests/bit_stream_test.cpp +++ b/tests/bit_stream_test.cpp @@ -1,196 +1,196 @@ #include "bit_stream.hpp" #include <ctime> #include <vector> #include <utility> #include <ctime> #include <cstdlib> #include <tut.h> namespace tut { struct bit_stream_data { static std::size_t bits_needed(int n) // bits needed to write the number { std::size_t shift = 32; do { shift -= 1; if (((n >> shift) & 0x1) == 1) { return shift + 1; } } while (shift != 0); return 1; } typedef std::pair<uint32, unsigned int> value_pair; }; typedef test_group<bit_stream_data> tg; - tg test_grp("bit_stream test"); + tg bit_stream_tg("bit_stream test"); template<> template<> void tg::object::test<1>() { set_test_name("test-only bit counting function test"); ensure_equals("bits for 7", bit_stream_data::bits_needed(7), 3); ensure_equals("bits for 0", bit_stream_data::bits_needed(0), 1); ensure_equals("bits for 1", bit_stream_data::bits_needed(1), 1); ensure_equals("bits for 12", bit_stream_data::bits_needed(12), 4); ensure_equals("bits for 65535", bit_stream_data::bits_needed(65535), 16); ensure_equals("bits for 2541252", bit_stream_data::bits_needed(2541252), 22); ensure_equals("bits for 2", bit_stream_data::bits_needed(2), 2); } template<> template<> void tg::object::test<2>() { set_test_name("mixed bit/uint/string reading and writing"); bit_stream bs(1); bs.write_bool(false); bs.write_bool(false); bs.write_bool(true); bs.write_bool(false); bs.write_bool(true); bs.write_bool(false); bs.write_bool(false); bs.write_bool(false); bs.write_bool(false); bs.write_string("abcdefgh10209420938"); std::vector<value_pair> values; // (value, bits_needed) values.push_back(std::make_pair(13, bit_stream_data::bits_needed(13))); values.push_back(std::make_pair(0, 12)); values.push_back(std::make_pair(2541252, bit_stream_data::bits_needed(2541252))); values.push_back(std::make_pair(123456, bit_stream_data::bits_needed(123456))); values.push_back(std::make_pair(1, 32)); values.push_back(std::make_pair(100, 32)); values.push_back(std::make_pair(11234, 32)); values.push_back(std::make_pair(0, bit_stream_data::bits_needed(0))); values.push_back(std::make_pair(1, bit_stream_data::bits_needed(1))); values.push_back(std::make_pair(3, bit_stream_data::bits_needed(3))); - for (std::vector<value_pair>::iterator i = values.begin(); + for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { bs.write_uint(i->first, i->second); } bs.write_string("OMG TEST"); bs.write_bool(false); bs.write_bool(true); bs.write_bool(true); bs.write_bool(false); bs.seek(0); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("string", bs.read_string(), "abcdefgh10209420938"); - for (std::vector<value_pair>::iterator i = values.begin(); + for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { ensure_equals("uint", bs.read_uint(i->second), i->first); } ensure_equals("string", bs.read_string(), "OMG TEST"); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); } template<> template<> void tg::object::test<3>() { set_test_name("random uint writing"); std::vector<value_pair> values; std::srand(static_cast<unsigned int>(time(0))); for (int i = 0; i < 10000; ++i) { int value = rand(); values.push_back(std::make_pair(value, bits_needed(value))); } bit_stream bs; - for (std::vector<value_pair>::iterator i = values.begin(); + for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { bs.write_uint(i->first, i->second); } bs.seek(0); - for (std::vector<value_pair>::iterator i = values.begin(); + for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { ensure_equals("uint", bs.read_uint(i->second), i->first); } } template<> template<> void tg::object::test<4>() { set_test_name("appending a bit stream"); bit_stream bs1; bit_stream bs2; bs1.write_uint(5, 8); bs2.write_uint(4, 4); bs2.write_uint(7, 3); std::size_t orig_size = bs1.size(); bs1.append(bs2); ensure_equals("size stays the same", bs1.size(), orig_size); bs1.write_uint(1, 1); bit_stream bs3; bs3.write_uint(1001, 32); bs1.append(bs3); bs1.write_uint(12, 4); bs1.seek(0); ensure_equals("uint", bs1.read_uint(8), 5); ensure_equals("uint", bs1.read_uint(4), 4); ensure_equals("uint", bs1.read_uint(3), 7); ensure_equals("uint", bs1.read_uint(1), 1); ensure_equals("uint", bs1.read_uint(32), 1001); ensure_equals("uint", bs1.read_uint(4), 12); } template<> template<> void tg::object::test<5>() { set_test_name("copy constructor and operator="); bit_stream bs1; bs1.write_uint(123); bs1.write_uint(321); bs1.seek(0); bit_stream bs2; bs2.write_uint(212); bs2 = bs1; bit_stream bs3(bs2); ensure_equals("original bs", bs1.read_uint(), 123); ensure_equals("original bs", bs1.read_uint(), 321); ensure_equals("operator= used", bs2.read_uint(), 123); ensure_equals("operator= used", bs2.read_uint(), 321); ensure_equals("copy constructor used", bs3.read_uint(), 123); ensure_equals("copy constructor used", bs3.read_uint(), 321); } }
darka/blahnet
e3e32c5fe0ca8363ea5cc11d3cb99db00cd32ffd
bit stream appending at any time
diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index 8cf480d..a9e9376 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,256 +1,257 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(false) { buffer = new buffer_type[size_]; memset(buffer, 0, size_); } bit_stream::bit_stream(bit_stream const& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) , allocated_externally(false) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(true) { } bit_stream::~bit_stream() { clear(); } bit_stream& bit_stream::operator=(bit_stream const& other) { clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); allocated_externally = false; return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } //std::cout << new_size << "\n"; resize(new_size); } void bit_stream::resize(std::size_t new_size) { assert(new_size >= size_); if (new_size == size_) return; buffer_type* new_buffer = new buffer_type[new_size]; // TODO: some redundancy here memset(new_buffer, 0, new_size); memcpy(new_buffer, buffer, size_); if (allocated_externally == false) delete[] buffer; allocated_externally = false; buffer = new_buffer; size_ = new_size; } void bit_stream::write_bool(bool n) { write_bit(n); } void bit_stream::write_uint(uint32 n, unsigned int bits) { // TODO: throw if bits > 32 assert(bits <= 32); affirm_size(bits); unsigned int i = 0; // How many bits we've already written while (i < bits) { unsigned int bits_to_write; // How many bits we'll be writing // There are 2 possibilities, either we're writing until the end of the byte on the buffer // or we aren't! We have to make the choice from either if ((8 - cur_rel_bit) <= (bits - i)) { // We get here if we're writing to the end of the current byte // on the buffer bits_to_write = 8 - cur_rel_bit; buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); ++cur_byte; } else { // We get here if writing all the bits we're still left to write // won't make us reach the end of the byte we're writing to bits_to_write = bits - i; uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); portion >>= cur_rel_bit; buffer[cur_byte] |= portion; } i += bits_to_write; cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; } } bool bit_stream::read_bool() { return read_bit(); } void bit_stream::write_sint(sint32 n, unsigned int bits) { write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { assert(bits <= 32); uint32 ret = 0; unsigned int i = 0; while (i < bits) { unsigned int bits_to_write; if ((bits - i) <= (8 - cur_rel_bit)) { // We're here because on the current byte in the buffer we have // bits to the right that we're supposed to skip bits_to_write = bits - i; uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; assert(bits_to_write <= 8); ret |= (portion >> (8 - bits_to_write)); } else { // We're here to read the current byte on the buffer from // cur_rel_bit till the end bits_to_write = 8 - cur_rel_bit; // Clear up the leftmost bits uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; portion >>= cur_rel_bit; assert(bits - i - bits_to_write <= bits); ret |= (portion << (bits - i - bits_to_write)); } i += bits_to_write; cur_rel_bit = cur_rel_bit + bits_to_write; if (cur_rel_bit >= 8) { ++cur_byte; cur_rel_bit %= 8; } } return ret; } sint32 bit_stream::read_sint(unsigned int bits) { return static_cast<sint32>(read_uint(bits)); } void bit_stream::write_string(std::string const& str) { write_uint(str.size(), 32); for (std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) { write_uint(*iter, 8); } } std::string bit_stream::read_string() { std::string ret; std::string::size_type chars = read_uint(32); for (std::string::size_type i = 0; i < chars; ++i) { ret.append(1, read_uint(8)); } return ret; } void bit_stream::append(bit_stream const& bs) { - // TODO: test this affirm_size(bs.cur_byte * 8 + bs.cur_rel_bit); if (cur_rel_bit == 0) { memcpy(buffer + cur_byte, bs.buffer, bs.cur_byte + (bs.cur_rel_bit > 0)); cur_byte += bs.cur_byte; cur_rel_bit = bs.cur_rel_bit; } else { - // TODO: finish this - assert(false); + for (std::size_t i = 0; i < bs.cur_byte + (bs.cur_rel_bit > 0); ++i) + { + write_uint(bs.buffer[i], 8); + } } } #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { if (buffer != 0 && allocated_externally == false) delete[] buffer; } void bit_stream::write_bit(bool bit) { affirm_size(1); buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); inc_bit(); } bool bit_stream::read_bit() { bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; inc_bit(); return ret; } void bit_stream::inc_bit() { cur_rel_bit += 1; if (cur_rel_bit == 8) { cur_byte += 1; cur_rel_bit = 0; } } diff --git a/tests/bit_stream_test.cpp b/tests/bit_stream_test.cpp index f4e15da..2e5c40b 100644 --- a/tests/bit_stream_test.cpp +++ b/tests/bit_stream_test.cpp @@ -1,192 +1,196 @@ #include "bit_stream.hpp" #include <ctime> #include <vector> #include <utility> #include <ctime> #include <cstdlib> #include <tut.h> namespace tut { struct bit_stream_data { static std::size_t bits_needed(int n) // bits needed to write the number { std::size_t shift = 32; do { shift -= 1; if (((n >> shift) & 0x1) == 1) { return shift + 1; } } while (shift != 0); return 1; } typedef std::pair<uint32, unsigned int> value_pair; }; typedef test_group<bit_stream_data> tg; tg test_grp("bit_stream test"); template<> template<> void tg::object::test<1>() { set_test_name("test-only bit counting function test"); ensure_equals("bits for 7", bit_stream_data::bits_needed(7), 3); ensure_equals("bits for 0", bit_stream_data::bits_needed(0), 1); ensure_equals("bits for 1", bit_stream_data::bits_needed(1), 1); ensure_equals("bits for 12", bit_stream_data::bits_needed(12), 4); ensure_equals("bits for 65535", bit_stream_data::bits_needed(65535), 16); ensure_equals("bits for 2541252", bit_stream_data::bits_needed(2541252), 22); ensure_equals("bits for 2", bit_stream_data::bits_needed(2), 2); } template<> template<> void tg::object::test<2>() { set_test_name("mixed bit/uint/string reading and writing"); bit_stream bs(1); bs.write_bool(false); bs.write_bool(false); bs.write_bool(true); bs.write_bool(false); bs.write_bool(true); bs.write_bool(false); bs.write_bool(false); bs.write_bool(false); bs.write_bool(false); bs.write_string("abcdefgh10209420938"); std::vector<value_pair> values; // (value, bits_needed) values.push_back(std::make_pair(13, bit_stream_data::bits_needed(13))); values.push_back(std::make_pair(0, 12)); values.push_back(std::make_pair(2541252, bit_stream_data::bits_needed(2541252))); values.push_back(std::make_pair(123456, bit_stream_data::bits_needed(123456))); values.push_back(std::make_pair(1, 32)); values.push_back(std::make_pair(100, 32)); values.push_back(std::make_pair(11234, 32)); values.push_back(std::make_pair(0, bit_stream_data::bits_needed(0))); values.push_back(std::make_pair(1, bit_stream_data::bits_needed(1))); values.push_back(std::make_pair(3, bit_stream_data::bits_needed(3))); for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { bs.write_uint(i->first, i->second); } bs.write_string("OMG TEST"); bs.write_bool(false); bs.write_bool(true); bs.write_bool(true); bs.write_bool(false); bs.seek(0); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("string", bs.read_string(), "abcdefgh10209420938"); for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { ensure_equals("uint", bs.read_uint(i->second), i->first); } ensure_equals("string", bs.read_string(), "OMG TEST"); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); } template<> template<> void tg::object::test<3>() { set_test_name("random uint writing"); std::vector<value_pair> values; std::srand(static_cast<unsigned int>(time(0))); for (int i = 0; i < 10000; ++i) { int value = rand(); values.push_back(std::make_pair(value, bits_needed(value))); } bit_stream bs; for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { bs.write_uint(i->first, i->second); } bs.seek(0); for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { ensure_equals("uint", bs.read_uint(i->second), i->first); } } template<> template<> void tg::object::test<4>() { set_test_name("appending a bit stream"); bit_stream bs1; bit_stream bs2; bs1.write_uint(5, 8); bs2.write_uint(4, 4); bs2.write_uint(7, 3); std::size_t orig_size = bs1.size(); bs1.append(bs2); ensure_equals("size stays the same", bs1.size(), orig_size); + bs1.write_uint(1, 1); - //bit_stream bs3; - //bs3.write_uint(1001, 32); - //bs1.append(bs3); + bit_stream bs3; + bs3.write_uint(1001, 32); + bs1.append(bs3); + bs1.write_uint(12, 4); bs1.seek(0); ensure_equals("uint", bs1.read_uint(8), 5); ensure_equals("uint", bs1.read_uint(4), 4); ensure_equals("uint", bs1.read_uint(3), 7); - //ensure_equals("uint", bs1.read_uint(32), 1001); + ensure_equals("uint", bs1.read_uint(1), 1); + ensure_equals("uint", bs1.read_uint(32), 1001); + ensure_equals("uint", bs1.read_uint(4), 12); } template<> template<> void tg::object::test<5>() { set_test_name("copy constructor and operator="); bit_stream bs1; bs1.write_uint(123); bs1.write_uint(321); bs1.seek(0); bit_stream bs2; bs2.write_uint(212); bs2 = bs1; bit_stream bs3(bs2); ensure_equals("original bs", bs1.read_uint(), 123); ensure_equals("original bs", bs1.read_uint(), 321); ensure_equals("operator= used", bs2.read_uint(), 123); ensure_equals("operator= used", bs2.read_uint(), 321); ensure_equals("copy constructor used", bs3.read_uint(), 123); ensure_equals("copy constructor used", bs3.read_uint(), 321); } }
darka/blahnet
aa456f425118d8e2d74eba1b0d9296cb8f27531d
spaces to tabs in a few places
diff --git a/src/address.hpp b/src/address.hpp index 98335aa..c889924 100644 --- a/src/address.hpp +++ b/src/address.hpp @@ -1,28 +1,28 @@ #ifndef UUID_8B00007D6BED43B1AF63C689D9D35D78 #define UUID_8B00007D6BED43B1AF63C689D9D35D78 struct sockaddr_in; /* TODO: implement copy constructor and operator= */ struct address { - address(); /* uses host's ip address and picks a port automatically */ - address(unsigned short int port); /* uses host's ip address and - uses given port */ - address(unsigned short int port, char const* ip); /* uses given ip - and port */ - address(address const& other); - ~address(); + address(); /* uses host's ip address and picks a port automatically */ + address(unsigned short int port); /* uses host's ip address and + uses given port */ + address(unsigned short int port, char const* ip); /* uses given ip + and port */ + address(address const& other); + ~address(); - address& operator=(address const& other); + address& operator=(address const& other); - /*unsigned short int port() const; - const char* ip() const;*/ - sockaddr_in const* data() const { return data_; } - sockaddr_in* data() { return data_; } - + /*unsigned short int port() const; + const char* ip() const;*/ + sockaddr_in const* data() const { return data_; } + sockaddr_in* data() { return data_; } + private: sockaddr_in* data_; }; #endif // UUID_8B00007D6BED43B1AF63C689D9D35D78 diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index 758cdad..8cf480d 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,256 +1,256 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(false) { - buffer = new buffer_type[size_]; + buffer = new buffer_type[size_]; memset(buffer, 0, size_); } bit_stream::bit_stream(bit_stream const& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) , allocated_externally(false) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(true) { } bit_stream::~bit_stream() { clear(); } bit_stream& bit_stream::operator=(bit_stream const& other) { clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); allocated_externally = false; return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } //std::cout << new_size << "\n"; resize(new_size); } void bit_stream::resize(std::size_t new_size) { assert(new_size >= size_); if (new_size == size_) return; buffer_type* new_buffer = new buffer_type[new_size]; // TODO: some redundancy here memset(new_buffer, 0, new_size); memcpy(new_buffer, buffer, size_); if (allocated_externally == false) delete[] buffer; allocated_externally = false; buffer = new_buffer; size_ = new_size; } void bit_stream::write_bool(bool n) { write_bit(n); } void bit_stream::write_uint(uint32 n, unsigned int bits) { - // TODO: throw if bits > 32 - assert(bits <= 32); - affirm_size(bits); - unsigned int i = 0; // How many bits we've already written - while (i < bits) - { - unsigned int bits_to_write; // How many bits we'll be writing - // There are 2 possibilities, either we're writing until the end of the byte on the buffer - // or we aren't! We have to make the choice from either - if ((8 - cur_rel_bit) <= (bits - i)) - { - // We get here if we're writing to the end of the current byte - // on the buffer - bits_to_write = 8 - cur_rel_bit; - buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); - ++cur_byte; - } - else - { - // We get here if writing all the bits we're still left to write - // won't make us reach the end of the byte we're writing to - bits_to_write = bits - i; - uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); - portion >>= cur_rel_bit; - buffer[cur_byte] |= portion; - } - i += bits_to_write; - cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; - } + // TODO: throw if bits > 32 + assert(bits <= 32); + affirm_size(bits); + unsigned int i = 0; // How many bits we've already written + while (i < bits) + { + unsigned int bits_to_write; // How many bits we'll be writing + // There are 2 possibilities, either we're writing until the end of the byte on the buffer + // or we aren't! We have to make the choice from either + if ((8 - cur_rel_bit) <= (bits - i)) + { + // We get here if we're writing to the end of the current byte + // on the buffer + bits_to_write = 8 - cur_rel_bit; + buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); + ++cur_byte; + } + else + { + // We get here if writing all the bits we're still left to write + // won't make us reach the end of the byte we're writing to + bits_to_write = bits - i; + uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); + portion >>= cur_rel_bit; + buffer[cur_byte] |= portion; + } + i += bits_to_write; + cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; + } } bool bit_stream::read_bool() { return read_bit(); } void bit_stream::write_sint(sint32 n, unsigned int bits) { - write_uint(static_cast<uint32>(n), bits); + write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { - assert(bits <= 32); - uint32 ret = 0; - unsigned int i = 0; - while (i < bits) - { - unsigned int bits_to_write; - if ((bits - i) <= (8 - cur_rel_bit)) - { - // We're here because on the current byte in the buffer we have - // bits to the right that we're supposed to skip - bits_to_write = bits - i; - uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; - - assert(bits_to_write <= 8); - ret |= (portion >> (8 - bits_to_write)); - } - else - { - // We're here to read the current byte on the buffer from - // cur_rel_bit till the end - bits_to_write = 8 - cur_rel_bit; - - // Clear up the leftmost bits - uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; - portion >>= cur_rel_bit; - - assert(bits - i - bits_to_write <= bits); - ret |= (portion << (bits - i - bits_to_write)); - } - i += bits_to_write; - cur_rel_bit = cur_rel_bit + bits_to_write; - if (cur_rel_bit >= 8) - { - ++cur_byte; - cur_rel_bit %= 8; - } - } - return ret; + assert(bits <= 32); + uint32 ret = 0; + unsigned int i = 0; + while (i < bits) + { + unsigned int bits_to_write; + if ((bits - i) <= (8 - cur_rel_bit)) + { + // We're here because on the current byte in the buffer we have + // bits to the right that we're supposed to skip + bits_to_write = bits - i; + uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; + + assert(bits_to_write <= 8); + ret |= (portion >> (8 - bits_to_write)); + } + else + { + // We're here to read the current byte on the buffer from + // cur_rel_bit till the end + bits_to_write = 8 - cur_rel_bit; + + // Clear up the leftmost bits + uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; + portion >>= cur_rel_bit; + + assert(bits - i - bits_to_write <= bits); + ret |= (portion << (bits - i - bits_to_write)); + } + i += bits_to_write; + cur_rel_bit = cur_rel_bit + bits_to_write; + if (cur_rel_bit >= 8) + { + ++cur_byte; + cur_rel_bit %= 8; + } + } + return ret; } sint32 bit_stream::read_sint(unsigned int bits) { - return static_cast<sint32>(read_uint(bits)); + return static_cast<sint32>(read_uint(bits)); } void bit_stream::write_string(std::string const& str) { - write_uint(str.size(), 32); - for (std::string::const_iterator iter = str.begin(); iter != str.end(); - ++iter) - { - write_uint(*iter, 8); - } + write_uint(str.size(), 32); + for (std::string::const_iterator iter = str.begin(); iter != str.end(); + ++iter) + { + write_uint(*iter, 8); + } } std::string bit_stream::read_string() { - std::string ret; - std::string::size_type chars = read_uint(32); - for (std::string::size_type i = 0; i < chars; ++i) - { - ret.append(1, read_uint(8)); - } - return ret; + std::string ret; + std::string::size_type chars = read_uint(32); + for (std::string::size_type i = 0; i < chars; ++i) + { + ret.append(1, read_uint(8)); + } + return ret; } void bit_stream::append(bit_stream const& bs) { // TODO: test this affirm_size(bs.cur_byte * 8 + bs.cur_rel_bit); if (cur_rel_bit == 0) { memcpy(buffer + cur_byte, bs.buffer, bs.cur_byte + (bs.cur_rel_bit > 0)); cur_byte += bs.cur_byte; cur_rel_bit = bs.cur_rel_bit; } else { // TODO: finish this assert(false); } } #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) - { + { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { if (buffer != 0 && allocated_externally == false) delete[] buffer; } void bit_stream::write_bit(bool bit) { affirm_size(1); buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); inc_bit(); } bool bit_stream::read_bit() { bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; inc_bit(); return ret; } void bit_stream::inc_bit() { cur_rel_bit += 1; if (cur_rel_bit == 8) { cur_byte += 1; cur_rel_bit = 0; } } diff --git a/src/bit_stream.hpp b/src/bit_stream.hpp index 0999df3..67bf142 100644 --- a/src/bit_stream.hpp +++ b/src/bit_stream.hpp @@ -1,63 +1,63 @@ #ifndef UUID_3A39D07169584AA1A5A6E890BF40AEC4 #define UUID_3A39D07169584AA1A5A6E890BF40AEC4 #include "types.hpp" #include <cstddef> #include <string> #include <stdexcept> // TODO: perhaps split class into read and write bit_streams struct bit_stream { typedef uint8 buffer_type; bit_stream(std::size_t size=4); bit_stream(bit_stream const& other); bit_stream(buffer_type* data, std::size_t size); ~bit_stream(); bit_stream& operator=(bit_stream const& other); void write_bool(bool n); bool read_bool(); void write_uint(uint32 n, unsigned int bits=32); uint32 read_uint(unsigned int bits=32); - + void write_sint(sint32 n, unsigned int bits=32); sint32 read_sint(unsigned int bits=32); - + void write_string(std::string const& str); std::string read_string(); void append(bit_stream const& bs); buffer_type const* raw_data() const { return buffer; } buffer_type* raw_data() { return buffer; } - std::size_t size() const { return size_; } + std::size_t size() const { return size_; } #if 0 void printContents() const; #endif void seek(unsigned int bit); private: void write_bit(bool bit); bool read_bit(); void inc_bit(); // increments cur_rel_bit and cur_byte if needed void affirm_size(std::size_t bits); void resize(std::size_t new_size); void clear(); buffer_type* buffer; std::size_t size_; std::size_t cur_byte; // current byte unsigned int cur_rel_bit; // relative to current byte bool allocated_externally; }; #endif // UUID_3A39D07169584AA1A5A6E890BF40AEC4
darka/blahnet
11a06edeb70c18cecf9e38595b6f684d3f545a32
appending, copy constructor, op= tests
diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index dca3641..758cdad 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,256 +1,256 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(false) { buffer = new buffer_type[size_]; memset(buffer, 0, size_); } bit_stream::bit_stream(bit_stream const& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) , allocated_externally(false) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) , allocated_externally(true) { } bit_stream::~bit_stream() { clear(); } bit_stream& bit_stream::operator=(bit_stream const& other) { clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); allocated_externally = false; return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } //std::cout << new_size << "\n"; resize(new_size); } void bit_stream::resize(std::size_t new_size) { assert(new_size >= size_); if (new_size == size_) return; buffer_type* new_buffer = new buffer_type[new_size]; // TODO: some redundancy here memset(new_buffer, 0, new_size); memcpy(new_buffer, buffer, size_); if (allocated_externally == false) delete[] buffer; allocated_externally = false; buffer = new_buffer; size_ = new_size; } void bit_stream::write_bool(bool n) { write_bit(n); } void bit_stream::write_uint(uint32 n, unsigned int bits) { // TODO: throw if bits > 32 assert(bits <= 32); affirm_size(bits); unsigned int i = 0; // How many bits we've already written while (i < bits) { unsigned int bits_to_write; // How many bits we'll be writing // There are 2 possibilities, either we're writing until the end of the byte on the buffer // or we aren't! We have to make the choice from either if ((8 - cur_rel_bit) <= (bits - i)) { // We get here if we're writing to the end of the current byte // on the buffer bits_to_write = 8 - cur_rel_bit; buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); ++cur_byte; } else { // We get here if writing all the bits we're still left to write // won't make us reach the end of the byte we're writing to bits_to_write = bits - i; uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); portion >>= cur_rel_bit; buffer[cur_byte] |= portion; } i += bits_to_write; cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; } } bool bit_stream::read_bool() { return read_bit(); } void bit_stream::write_sint(sint32 n, unsigned int bits) { write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { assert(bits <= 32); uint32 ret = 0; unsigned int i = 0; while (i < bits) { unsigned int bits_to_write; if ((bits - i) <= (8 - cur_rel_bit)) { // We're here because on the current byte in the buffer we have // bits to the right that we're supposed to skip bits_to_write = bits - i; uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; assert(bits_to_write <= 8); ret |= (portion >> (8 - bits_to_write)); } else { // We're here to read the current byte on the buffer from // cur_rel_bit till the end bits_to_write = 8 - cur_rel_bit; // Clear up the leftmost bits uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; portion >>= cur_rel_bit; assert(bits - i - bits_to_write <= bits); ret |= (portion << (bits - i - bits_to_write)); } i += bits_to_write; cur_rel_bit = cur_rel_bit + bits_to_write; if (cur_rel_bit >= 8) { ++cur_byte; cur_rel_bit %= 8; } } return ret; } sint32 bit_stream::read_sint(unsigned int bits) { return static_cast<sint32>(read_uint(bits)); } void bit_stream::write_string(std::string const& str) { write_uint(str.size(), 32); for (std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) { write_uint(*iter, 8); } } std::string bit_stream::read_string() { std::string ret; std::string::size_type chars = read_uint(32); for (std::string::size_type i = 0; i < chars; ++i) { ret.append(1, read_uint(8)); } return ret; } void bit_stream::append(bit_stream const& bs) { // TODO: test this affirm_size(bs.cur_byte * 8 + bs.cur_rel_bit); if (cur_rel_bit == 0) { - memcpy(buffer + cur_byte, bs.buffer, bs.size()); + memcpy(buffer + cur_byte, bs.buffer, bs.cur_byte + (bs.cur_rel_bit > 0)); cur_byte += bs.cur_byte; cur_rel_bit = bs.cur_rel_bit; } else { // TODO: finish this assert(false); } } #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { if (buffer != 0 && allocated_externally == false) delete[] buffer; } void bit_stream::write_bit(bool bit) { affirm_size(1); buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); inc_bit(); } bool bit_stream::read_bit() { bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; inc_bit(); return ret; } void bit_stream::inc_bit() { cur_rel_bit += 1; if (cur_rel_bit == 8) { cur_byte += 1; cur_rel_bit = 0; } } diff --git a/src/bit_stream.hpp b/src/bit_stream.hpp index 11e6adc..0999df3 100644 --- a/src/bit_stream.hpp +++ b/src/bit_stream.hpp @@ -1,65 +1,63 @@ #ifndef UUID_3A39D07169584AA1A5A6E890BF40AEC4 #define UUID_3A39D07169584AA1A5A6E890BF40AEC4 #include "types.hpp" #include <cstddef> #include <string> #include <stdexcept> // TODO: perhaps split class into read and write bit_streams struct bit_stream { typedef uint8 buffer_type; - // TODO: TEST copy constructor and operator=, they're - // completely untested bit_stream(std::size_t size=4); bit_stream(bit_stream const& other); bit_stream(buffer_type* data, std::size_t size); ~bit_stream(); bit_stream& operator=(bit_stream const& other); void write_bool(bool n); bool read_bool(); void write_uint(uint32 n, unsigned int bits=32); - uint32 read_uint(unsigned int bits); + uint32 read_uint(unsigned int bits=32); void write_sint(sint32 n, unsigned int bits=32); - sint32 read_sint(unsigned int bits); + sint32 read_sint(unsigned int bits=32); void write_string(std::string const& str); std::string read_string(); void append(bit_stream const& bs); buffer_type const* raw_data() const { return buffer; } buffer_type* raw_data() { return buffer; } std::size_t size() const { return size_; } #if 0 void printContents() const; #endif void seek(unsigned int bit); private: void write_bit(bool bit); bool read_bit(); void inc_bit(); // increments cur_rel_bit and cur_byte if needed void affirm_size(std::size_t bits); void resize(std::size_t new_size); void clear(); buffer_type* buffer; std::size_t size_; std::size_t cur_byte; // current byte unsigned int cur_rel_bit; // relative to current byte bool allocated_externally; }; #endif // UUID_3A39D07169584AA1A5A6E890BF40AEC4 diff --git a/tests/bit_stream_test.cpp b/tests/bit_stream_test.cpp index c38ce2c..f4e15da 100644 --- a/tests/bit_stream_test.cpp +++ b/tests/bit_stream_test.cpp @@ -1,144 +1,192 @@ #include "bit_stream.hpp" #include <ctime> #include <vector> #include <utility> #include <ctime> #include <cstdlib> #include <tut.h> namespace tut { struct bit_stream_data { static std::size_t bits_needed(int n) // bits needed to write the number { std::size_t shift = 32; do { shift -= 1; if (((n >> shift) & 0x1) == 1) { return shift + 1; } } while (shift != 0); return 1; } typedef std::pair<uint32, unsigned int> value_pair; }; typedef test_group<bit_stream_data> tg; tg test_grp("bit_stream test"); template<> template<> void tg::object::test<1>() { set_test_name("test-only bit counting function test"); ensure_equals("bits for 7", bit_stream_data::bits_needed(7), 3); ensure_equals("bits for 0", bit_stream_data::bits_needed(0), 1); ensure_equals("bits for 1", bit_stream_data::bits_needed(1), 1); ensure_equals("bits for 12", bit_stream_data::bits_needed(12), 4); ensure_equals("bits for 65535", bit_stream_data::bits_needed(65535), 16); ensure_equals("bits for 2541252", bit_stream_data::bits_needed(2541252), 22); ensure_equals("bits for 2", bit_stream_data::bits_needed(2), 2); } template<> template<> void tg::object::test<2>() { set_test_name("mixed bit/uint/string reading and writing"); bit_stream bs(1); bs.write_bool(false); bs.write_bool(false); bs.write_bool(true); bs.write_bool(false); bs.write_bool(true); bs.write_bool(false); bs.write_bool(false); bs.write_bool(false); bs.write_bool(false); bs.write_string("abcdefgh10209420938"); std::vector<value_pair> values; // (value, bits_needed) values.push_back(std::make_pair(13, bit_stream_data::bits_needed(13))); values.push_back(std::make_pair(0, 12)); values.push_back(std::make_pair(2541252, bit_stream_data::bits_needed(2541252))); values.push_back(std::make_pair(123456, bit_stream_data::bits_needed(123456))); values.push_back(std::make_pair(1, 32)); values.push_back(std::make_pair(100, 32)); values.push_back(std::make_pair(11234, 32)); values.push_back(std::make_pair(0, bit_stream_data::bits_needed(0))); values.push_back(std::make_pair(1, bit_stream_data::bits_needed(1))); values.push_back(std::make_pair(3, bit_stream_data::bits_needed(3))); for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { bs.write_uint(i->first, i->second); } bs.write_string("OMG TEST"); bs.write_bool(false); bs.write_bool(true); bs.write_bool(true); bs.write_bool(false); bs.seek(0); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), false); ensure_equals("string", bs.read_string(), "abcdefgh10209420938"); for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { ensure_equals("uint", bs.read_uint(i->second), i->first); } ensure_equals("string", bs.read_string(), "OMG TEST"); ensure_equals("bool", bs.read_bool(), false); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), true); ensure_equals("bool", bs.read_bool(), false); } template<> template<> void tg::object::test<3>() { set_test_name("random uint writing"); std::vector<value_pair> values; std::srand(static_cast<unsigned int>(time(0))); for (int i = 0; i < 10000; ++i) { int value = rand(); values.push_back(std::make_pair(value, bits_needed(value))); } bit_stream bs; for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { bs.write_uint(i->first, i->second); } bs.seek(0); for (std::vector<value_pair>::iterator i = values.begin(); i != values.end(); ++i) { ensure_equals("uint", bs.read_uint(i->second), i->first); } } + + template<> template<> + void tg::object::test<4>() + { + set_test_name("appending a bit stream"); + bit_stream bs1; + bit_stream bs2; + bs1.write_uint(5, 8); + bs2.write_uint(4, 4); + bs2.write_uint(7, 3); + std::size_t orig_size = bs1.size(); + + bs1.append(bs2); + ensure_equals("size stays the same", bs1.size(), orig_size); + + //bit_stream bs3; + //bs3.write_uint(1001, 32); + //bs1.append(bs3); + bs1.seek(0); + + ensure_equals("uint", bs1.read_uint(8), 5); + ensure_equals("uint", bs1.read_uint(4), 4); + ensure_equals("uint", bs1.read_uint(3), 7); + //ensure_equals("uint", bs1.read_uint(32), 1001); + } + + + template<> template<> + void tg::object::test<5>() + { + set_test_name("copy constructor and operator="); + bit_stream bs1; + bs1.write_uint(123); + bs1.write_uint(321); + bs1.seek(0); + + bit_stream bs2; + bs2.write_uint(212); + bs2 = bs1; + + bit_stream bs3(bs2); + ensure_equals("original bs", bs1.read_uint(), 123); + ensure_equals("original bs", bs1.read_uint(), 321); + ensure_equals("operator= used", bs2.read_uint(), 123); + ensure_equals("operator= used", bs2.read_uint(), 321); + ensure_equals("copy constructor used", bs3.read_uint(), 123); + ensure_equals("copy constructor used", bs3.read_uint(), 321); + } }
darka/blahnet
737e2dbd6981f226ee238b2a7a5345ae80d95340
half-implemented server class; bit_stream unit test
diff --git a/CMakeLists.txt b/CMakeLists.txt index 648fb39..35c0899 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,30 +1,38 @@ cmake_minimum_required(VERSION 2.4) project(NetNet) include_directories(src) file(GLOB main_sources src/*.cpp) file(GLOB server_sources server/*.cpp) file(GLOB client_sources client/*.cpp) +file(GLOB tests_sources tests/*.cpp) if(WIN32) add_definitions(-DBLAHNET_WIN32) endif(WIN32) if(UNIX) - set(CMAKE_CXX_FLAGS "-std=c++98 -Wall -Wextra -pedantic -ggdb3") + set(CMAKE_CXX_FLAGS "-Wall -Wextra -ggdb3") endif(UNIX) add_library(netnet STATIC ${main_sources}) # for testing add_executable(netnet-server ${server_sources}) add_executable(netnet-client ${client_sources}) +add_executable(test-all ${tests_sources}) + +set(LINK_LIBS netnet boost_signals) +set(WIN32_LINK_LIBS ${LINK_LIBS} wsock32) + if(WIN32) - target_link_libraries(netnet-server netnet wsock32) - target_link_libraries(netnet-client netnet wsock32) + target_link_libraries(netnet-server ${WIN32_LINK_LIBS}) + target_link_libraries(test-all ${WIN32_LINK_LIBS}) + target_link_libraries(netnet-client ${WIN32_LINK_LIBS}) else(WIN32) - target_link_libraries(netnet-server netnet) - target_link_libraries(netnet-client netnet) + target_link_libraries(netnet-server ${LINK_LIBS}) + target_link_libraries(netnet-client ${LINK_LIBS}) + target_link_libraries(test-all ${LINK_LIBS}) endif(WIN32) diff --git a/client/client.cpp b/client/client_test.cpp similarity index 61% rename from client/client.cpp rename to client/client_test.cpp index 5c228d5..6b71a36 100644 --- a/client/client.cpp +++ b/client/client_test.cpp @@ -1,9 +1,8 @@ -#include "reliable_layer.hpp" int main() { - reliable_layer rel_link; + /*reliable_layer rel_link; address addr(23232, "127.0.0.1"); char msg[] = "lol wat"; rel_link.sendto(msg, strlen(msg), addr); - rel_link.work(); + rel_link.work();*/ } diff --git a/server/server.cpp b/server/server.cpp deleted file mode 100644 index bd4f4cb..0000000 --- a/server/server.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "udp_socket.hpp" -#include <iostream> - -int main() -{ - udp_socket sock; - sock.create(); - sock.bind(23232); - address receiver_addr; - char buf[100]; - int bytes = sock.recvfrom(buf, 99, receiver_addr); - std::cout << bytes << "\n"; -} diff --git a/server/server_test.cpp b/server/server_test.cpp new file mode 100644 index 0000000..3620010 --- /dev/null +++ b/server/server_test.cpp @@ -0,0 +1,17 @@ +#include "server.hpp" +#include <iostream> + +int main() +{ + /*udp_socket sock; + sock.create(); + sock.bind(23232); + address receiver_addr; + char buf[100]; + int bytes = sock.recvfrom(buf, 99, receiver_addr);*/ + server serv; + serv.host(23232); + + + //std::cout << bytes << "\n"; +} diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index c06ad2f..dca3641 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,234 +1,256 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) +, allocated_externally(false) { buffer = new buffer_type[size_]; memset(buffer, 0, size_); } -bit_stream::bit_stream(const bit_stream& other) +bit_stream::bit_stream(bit_stream const& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) +, allocated_externally(false) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) +, allocated_externally(true) { } bit_stream::~bit_stream() { clear(); } -bit_stream& bit_stream::operator=(const bit_stream& other) +bit_stream& bit_stream::operator=(bit_stream const& other) { clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); + allocated_externally = false; return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } - if (new_size > size_) - { - std::cout << new_size << "\n"; - resize(new_size); - } + //std::cout << new_size << "\n"; + resize(new_size); } void bit_stream::resize(std::size_t new_size) { + assert(new_size >= size_); + if (new_size == size_) + return; buffer_type* new_buffer = new buffer_type[new_size]; // TODO: some redundancy here memset(new_buffer, 0, new_size); memcpy(new_buffer, buffer, size_); - delete[] buffer; + if (allocated_externally == false) + delete[] buffer; + allocated_externally = false; buffer = new_buffer; size_ = new_size; } void bit_stream::write_bool(bool n) { write_bit(n); } void bit_stream::write_uint(uint32 n, unsigned int bits) { // TODO: throw if bits > 32 assert(bits <= 32); affirm_size(bits); unsigned int i = 0; // How many bits we've already written while (i < bits) { unsigned int bits_to_write; // How many bits we'll be writing // There are 2 possibilities, either we're writing until the end of the byte on the buffer // or we aren't! We have to make the choice from either if ((8 - cur_rel_bit) <= (bits - i)) { // We get here if we're writing to the end of the current byte // on the buffer bits_to_write = 8 - cur_rel_bit; buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); ++cur_byte; } else { // We get here if writing all the bits we're still left to write // won't make us reach the end of the byte we're writing to bits_to_write = bits - i; uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); portion >>= cur_rel_bit; buffer[cur_byte] |= portion; } i += bits_to_write; cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; } } bool bit_stream::read_bool() { return read_bit(); } void bit_stream::write_sint(sint32 n, unsigned int bits) { write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { assert(bits <= 32); uint32 ret = 0; unsigned int i = 0; while (i < bits) { unsigned int bits_to_write; if ((bits - i) <= (8 - cur_rel_bit)) { // We're here because on the current byte in the buffer we have // bits to the right that we're supposed to skip bits_to_write = bits - i; uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; assert(bits_to_write <= 8); ret |= (portion >> (8 - bits_to_write)); } else { // We're here to read the current byte on the buffer from // cur_rel_bit till the end bits_to_write = 8 - cur_rel_bit; // Clear up the leftmost bits uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; portion >>= cur_rel_bit; assert(bits - i - bits_to_write <= bits); ret |= (portion << (bits - i - bits_to_write)); } i += bits_to_write; cur_rel_bit = cur_rel_bit + bits_to_write; if (cur_rel_bit >= 8) { ++cur_byte; cur_rel_bit %= 8; } } return ret; } sint32 bit_stream::read_sint(unsigned int bits) { return static_cast<sint32>(read_uint(bits)); } -void bit_stream::write_string(const std::string& str) +void bit_stream::write_string(std::string const& str) { write_uint(str.size(), 32); for (std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) { write_uint(*iter, 8); } } std::string bit_stream::read_string() { std::string ret; std::string::size_type chars = read_uint(32); for (std::string::size_type i = 0; i < chars; ++i) { ret.append(1, read_uint(8)); } return ret; } +void bit_stream::append(bit_stream const& bs) +{ + // TODO: test this + affirm_size(bs.cur_byte * 8 + bs.cur_rel_bit); + if (cur_rel_bit == 0) + { + memcpy(buffer + cur_byte, bs.buffer, bs.size()); + cur_byte += bs.cur_byte; + cur_rel_bit = bs.cur_rel_bit; + } + else + { + // TODO: finish this + assert(false); + } +} #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { - if (buffer != 0) + if (buffer != 0 && allocated_externally == false) delete[] buffer; } void bit_stream::write_bit(bool bit) { affirm_size(1); buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); inc_bit(); } bool bit_stream::read_bit() { bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; inc_bit(); return ret; } void bit_stream::inc_bit() { cur_rel_bit += 1; if (cur_rel_bit == 8) { cur_byte += 1; cur_rel_bit = 0; } } diff --git a/src/bit_stream.hpp b/src/bit_stream.hpp index c718372..11e6adc 100644 --- a/src/bit_stream.hpp +++ b/src/bit_stream.hpp @@ -1,59 +1,65 @@ #ifndef UUID_3A39D07169584AA1A5A6E890BF40AEC4 #define UUID_3A39D07169584AA1A5A6E890BF40AEC4 #include "types.hpp" #include <cstddef> #include <string> #include <stdexcept> +// TODO: perhaps split class into read and write bit_streams + struct bit_stream { typedef uint8 buffer_type; - // TODO: implement copy constructor and operator= + // TODO: TEST copy constructor and operator=, they're + // completely untested bit_stream(std::size_t size=4); - bit_stream(const bit_stream& other); + bit_stream(bit_stream const& other); bit_stream(buffer_type* data, std::size_t size); ~bit_stream(); - bit_stream& operator=(const bit_stream& other); + bit_stream& operator=(bit_stream const& other); void write_bool(bool n); bool read_bool(); void write_uint(uint32 n, unsigned int bits=32); uint32 read_uint(unsigned int bits); void write_sint(sint32 n, unsigned int bits=32); sint32 read_sint(unsigned int bits); - void write_string(const std::string& str); + void write_string(std::string const& str); std::string read_string(); - const buffer_type* raw_data() const { return buffer; } + void append(bit_stream const& bs); + + buffer_type const* raw_data() const { return buffer; } buffer_type* raw_data() { return buffer; } std::size_t size() const { return size_; } #if 0 void printContents() const; #endif void seek(unsigned int bit); private: void write_bit(bool bit); bool read_bit(); void inc_bit(); // increments cur_rel_bit and cur_byte if needed void affirm_size(std::size_t bits); void resize(std::size_t new_size); void clear(); buffer_type* buffer; std::size_t size_; std::size_t cur_byte; // current byte unsigned int cur_rel_bit; // relative to current byte + bool allocated_externally; }; #endif // UUID_3A39D07169584AA1A5A6E890BF40AEC4 diff --git a/src/link.cpp b/src/link.cpp deleted file mode 100644 index e3989e9..0000000 --- a/src/link.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "link.hpp" - -// TODO: error handling with exceptions - -link::link() -{ -} - -link::~link() -{ - sock.close(); -} - diff --git a/src/link_common.cpp b/src/link_common.cpp new file mode 100644 index 0000000..eb43bb0 --- /dev/null +++ b/src/link_common.cpp @@ -0,0 +1,13 @@ +#include "link_common.hpp" + +// TODO: error handling with exceptions + +link_common::link_common() +{ +} + +link_common::~link_common() +{ + sock.close(); +} + diff --git a/src/link.hpp b/src/link_common.hpp similarity index 56% rename from src/link.hpp rename to src/link_common.hpp index 417ee7b..6db5f68 100644 --- a/src/link.hpp +++ b/src/link_common.hpp @@ -1,32 +1,48 @@ #ifndef UUID_52DA523EF9CE4CF3A46629AAEC07E467 #define UUID_52DA523EF9CE4CF3A46629AAEC07E467 #include "bit_stream.hpp" #include "udp_socket.hpp" #include <boost/signal.hpp> +#include <queue> -// TODO: rename to link_common -struct link +struct link_common { enum disconnection_reason { timeout = 0, voluntary = 1 }; + enum message_type + { + reliable_ordered = 0 + /* + unreliable_ordered = 1, + reliable_unordered = 2, + unreliable_unordered = 3, + */ + }; - ~link(); + ~link_common(); //void host(unsigned short int port); //void connect(address const& addr); //void send(bit_stream const& data); + static uint8 const header_size = 2; // in bytes + static uint8 const protocol_version = 0; + // Header: + // 4 bits: protocol id + // 8 bits: unique peer id + // 3 bits: message type + // 1 bit : is an ack packet protected: - link(); + link_common(); //bool connected; //address addr; udp_socket sock; - static uint8 const protocol_version = 0; + //std::queue<packet*> packets; }; #endif // UUID_52DA523EF9CE4CF3A46629AAEC07E467 diff --git a/src/packet.cpp b/src/packet.cpp deleted file mode 100644 index 73f1825..0000000 --- a/src/packet.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include "packet.hpp" - -packet::packet(char const* msg, std::size_t msg_len, - uint8 peer_id, uint8 seq_num, - address const& addr) -{ - -} diff --git a/src/packet.hpp b/src/packet.hpp deleted file mode 100644 index 32f43ff..0000000 --- a/src/packet.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef UUID_75A46991F81648ED83D9A7E8D598BE9D -#define UUID_75A46991F81648ED83D9A7E8D598BE9D - -#include "types.hpp" - -struct packet -{ - packet(char const* msg, std::size_t msg_len, - uint8 peer_id, uint8 seq_num, - address const& addr); // message with a header - // TODO: ack packets should contain multiple acks - packet(uint8 peer_id, uint8 seq_num, - address const& addr); // ack packet - ~packet(); - - char* msg() { return msg; } - std::size_t msg_len() { msg_len_; } - address const& addr() { return addr_; } - -private: - char* msg_; - std::size_t msg_len_; - address const& addr_; -}; - -#endif // UUID_75A46991F81648ED83D9A7E8D598BE9D diff --git a/src/peer.cpp b/src/peer.cpp index f50f85d..b630652 100644 --- a/src/peer.cpp +++ b/src/peer.cpp @@ -1,9 +1,9 @@ #include "peer.hpp" peer::peer(address const& addr) -: addr(addr) -, incoming_seq_number(0) -, outgoing_seq_number(0) +: addr_(addr) +, incoming_seq_number_(0) +, outgoing_seq_number_(0) { } diff --git a/src/reliable_layer.cpp b/src/reliable_layer.cpp deleted file mode 100644 index 4f1acc5..0000000 --- a/src/reliable_layer.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "reliable_layer.hpp" -#include <cassert> -#include <cstring> - -reliable_layer::reliable_layer() -: seq_num(0) -, expecting(false) -, expected_num(0) -{ - sock.create(); - sock.set_nonblocking(); -} - -reliable_layer::~reliable_layer() -{ - while (!packets.empty()) - { - pop_top_packet(); - } -} - -void reliable_layer::work() -{ - // receive packets - // TODO: enforce default max packet size everywhere? - unsigned int const packet_size = 20; - char msg[packet_size]; - address addr; - int result = sock.recvfrom(msg, packet_size - 1, addr); - if (result != -1) - { - // TODO: should disconnect the client instead - assert((msg[0] >> 1) == protocol_version); - // is packet an ack? - if ((msg[0] & 0x1) == 0) - { - if (expecting && msg[1] == expected_num) - pop_top_packet(); - } - else - { - // send an ack - // TODO: pack many acks in one packet - } - - } - - if (packets.empty()) - { - expecting = false; - } - else - { - // send top packet - packet* current_packet = packets.front(); - // TODO: error checking - sock.sendto(current_packet->msg, current_packet->msg_len, - current_packet->addr); - expecting = true; - expected_num = current_packet->msg[1]; - pop_top_packet(); - } - -} - -void reliable_layer::pop_top_packet() -{ - packet* current_packet = packets.front(); - delete[] current_packet->msg; - delete current_packet; - packets.pop(); -} diff --git a/src/reliable_layer.hpp b/src/reliable_layer.hpp deleted file mode 100644 index 1f1e654..0000000 --- a/src/reliable_layer.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef UUID_073328F7899A4DD0B86369768768AFE7 -#define UUID_073328F7899A4DD0B86369768768AFE7 - -#include "udp_socket.hpp" -#include "bit_stream.hpp" -#include "types.hpp" -#include <queue> -#include <utility> - -struct reliable_layer -{ - reliable_layer(); - ~reliable_layer(); - void sendto(char const* msg, std::size_t msg_len, - address const& addr); - void work(); - -private: - - void pop_top_packet(); // handles memory - - udp_socket sock; - uint8 seq_num; // sequence number used in sent message header - bool expecting; // if expecting ack packets - uint8 expected_num; // sequence number we're waiting for - std::queue<packet*> packets; - static uint8 const protocol_version = 0; -}; - -#endif // UUID_073328F7899A4DD0B86369768768AFE7 - diff --git a/src/server.cpp b/src/server.cpp index 4a0b68e..228472e 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1,86 +1,101 @@ #include "server.hpp" +#include "bit_stream.hpp" server::server() : expecting(false) { } void server::host(unsigned short int port) { sock.create(); sock.bind(port); } void server::work() { // receive packets // TODO: enforce default max packet size everywhere? - // should go into link.hpp if so + // should go into link_common if so + // If anything we need to check the size isn't too small unsigned int const packet_size = 20; - char msg[packet_size]; + char raw_msg[packet_size]; address addr; - int result = sock.recvfrom(msg, packet_size - 1, addr); + int result = sock.recvfrom(raw_msg, packet_size - 1, addr); + bit_stream msg(reinterpret_cast<uint8*>(raw_msg), packet_size); if (result != -1) { // TODO: should disconnect the client instead - assert((msg[0] >> 1) == protocol_version); + assert((msg.read_uint(4)) == protocol_version); + // TODO: check if such peer exists at all + peer* sender = peers[msg.read_uint(8)]; + uint8 msg_type = msg.read_uint(3); + // is packet an ack? - if ((msg[0] & 0x1) == 0) + if (msg.read_uint(1)) { - if (expecting && msg[1] == expected_num) - pop_top_packet(); + uint8 seq_number = msg.read_uint(8); + //if (expecting && seq_number == sender->outgoing_seq_number()) + // pop_top_packet(); } else { // send an ack // TODO: pack many acks in one packet } } - if (packets.empty()) + /*if (packets.empty()) { expecting = false; } else { // send top packet packet* current_packet = packets.front(); // TODO: error checking sock.sendto(current_packet->msg, current_packet->msg_len, current_packet->addr); expecting = true; expected_num = current_packet->msg[1]; pop_top_packet(); - } + }*/ } void server::stop() { sock.close(); } -void server::sendto(char const* msg, std::size_t msg_len, +void server::sendto(char* msg, std::size_t msg_len, uint8 peer_id) { // TODO: split the packet here? need to guard against overflow anyway - std::size_t prepared_msg_len = msg_len + 2; + /*std::size_t prepared_msg_len = msg_len + 2; char* prepared_msg = new char[prepared_msg_len]; std::memcpy(prepared_msg + 2, msg, msg_len); std::memset(prepared_msg, 0, 2); // attach header // first 7 bits = protocol version // TODO: (how else do we do this? on connection? look at q3 prepared_msg[0] |= (protocol_version << 1); // we're not sending an ack packet, so the 8th bit is 1 prepared_msg[0] |= 1; // attach sequence number - prepared_msg[1] |= seq_num; + prepared_msg[1] |= seq_num;*/ + bit_stream bs(reinterpret_cast<bit_stream::buffer_type*>(msg), msg_len); + bit_stream packet(header_size); + packet.write_uint(protocol_version); + packet.write_uint(peer_id); + packet.write_uint(reliable_ordered); + packet.write_uint(false); // not an ack packet + packet.append(bs); // store in a queue? - packets.push(new packet(prepared_msg, prepared_msg_len, addr)); - seq_num += 1; + //packets.push(packet); + counters[reliable_ordered] += 1; } diff --git a/src/server.hpp b/src/server.hpp index 1ec1015..b61308c 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -1,31 +1,32 @@ #ifndef UUID_A3C8588901A048B6B6FB438C5F31BBCF #define UUID_A3C8588901A048B6B6FB438C5F31BBCF -#include "link.hpp" +#include "link_common.hpp" #include "peer.hpp" #include <map> -struct server : public link +struct server : public link_common { server(); void host(unsigned short int port); void work(); void stop(); // does nothing if not hosting - void sendto(char const* msg, std::size_t msg_len, + void sendto(char* msg, std::size_t msg_len, uint8 peer_id); // TODO: how to cache the addresses? ??? boost::signal<void (address const&)> on_connect; boost::signal<void (address const&, disconnection_reason const&)> on_disconnect; boost::signal<void (address const&, bit_stream const&)> on_receive; private: - std::map<uint8, peer> peers; // unique peer id => peer + std::map<uint8, peer*> peers; // unique peer id => peer + std::map<message_type, uint8> counters; bool expecting; }; #endif // UUID_A3C8588901A048B6B6FB438C5F31BBCF diff --git a/tests/bit_stream_test.cpp b/tests/bit_stream_test.cpp new file mode 100644 index 0000000..c38ce2c --- /dev/null +++ b/tests/bit_stream_test.cpp @@ -0,0 +1,144 @@ +#include "bit_stream.hpp" +#include <ctime> +#include <vector> +#include <utility> +#include <ctime> +#include <cstdlib> +#include <tut.h> + +namespace tut +{ + struct bit_stream_data + { + static std::size_t bits_needed(int n) // bits needed to write the number + { + std::size_t shift = 32; + do + { + shift -= 1; + if (((n >> shift) & 0x1) == 1) + { + return shift + 1; + } + } while (shift != 0); + return 1; + } + typedef std::pair<uint32, unsigned int> value_pair; + }; + + typedef test_group<bit_stream_data> tg; + tg test_grp("bit_stream test"); + + template<> template<> + void tg::object::test<1>() + { + set_test_name("test-only bit counting function test"); + ensure_equals("bits for 7", bit_stream_data::bits_needed(7), 3); + ensure_equals("bits for 0", bit_stream_data::bits_needed(0), 1); + ensure_equals("bits for 1", bit_stream_data::bits_needed(1), 1); + ensure_equals("bits for 12", bit_stream_data::bits_needed(12), 4); + ensure_equals("bits for 65535", bit_stream_data::bits_needed(65535), 16); + ensure_equals("bits for 2541252", bit_stream_data::bits_needed(2541252), 22); + ensure_equals("bits for 2", bit_stream_data::bits_needed(2), 2); + } + + template<> template<> + void tg::object::test<2>() + { + set_test_name("mixed bit/uint/string reading and writing"); + bit_stream bs(1); + + bs.write_bool(false); + bs.write_bool(false); + bs.write_bool(true); + bs.write_bool(false); + + bs.write_bool(true); + bs.write_bool(false); + bs.write_bool(false); + bs.write_bool(false); + + bs.write_bool(false); + + bs.write_string("abcdefgh10209420938"); + + std::vector<value_pair> values; // (value, bits_needed) + values.push_back(std::make_pair(13, bit_stream_data::bits_needed(13))); + values.push_back(std::make_pair(0, 12)); + values.push_back(std::make_pair(2541252, bit_stream_data::bits_needed(2541252))); + values.push_back(std::make_pair(123456, bit_stream_data::bits_needed(123456))); + values.push_back(std::make_pair(1, 32)); + values.push_back(std::make_pair(100, 32)); + values.push_back(std::make_pair(11234, 32)); + values.push_back(std::make_pair(0, bit_stream_data::bits_needed(0))); + values.push_back(std::make_pair(1, bit_stream_data::bits_needed(1))); + values.push_back(std::make_pair(3, bit_stream_data::bits_needed(3))); + for (std::vector<value_pair>::iterator i = values.begin(); + i != values.end(); ++i) + { + bs.write_uint(i->first, i->second); + } + + bs.write_string("OMG TEST"); + + bs.write_bool(false); + bs.write_bool(true); + bs.write_bool(true); + bs.write_bool(false); + + bs.seek(0); + + ensure_equals("bool", bs.read_bool(), false); + ensure_equals("bool", bs.read_bool(), false); + ensure_equals("bool", bs.read_bool(), true); + ensure_equals("bool", bs.read_bool(), false); + + ensure_equals("bool", bs.read_bool(), true); + ensure_equals("bool", bs.read_bool(), false); + ensure_equals("bool", bs.read_bool(), false); + ensure_equals("bool", bs.read_bool(), false); + + ensure_equals("bool", bs.read_bool(), false); + + ensure_equals("string", bs.read_string(), "abcdefgh10209420938"); + + for (std::vector<value_pair>::iterator i = values.begin(); + i != values.end(); ++i) + { + ensure_equals("uint", bs.read_uint(i->second), i->first); + } + + ensure_equals("string", bs.read_string(), "OMG TEST"); + + ensure_equals("bool", bs.read_bool(), false); + ensure_equals("bool", bs.read_bool(), true); + ensure_equals("bool", bs.read_bool(), true); + ensure_equals("bool", bs.read_bool(), false); + } + + template<> template<> + void tg::object::test<3>() + { + set_test_name("random uint writing"); + std::vector<value_pair> values; + std::srand(static_cast<unsigned int>(time(0))); + for (int i = 0; i < 10000; ++i) + { + int value = rand(); + values.push_back(std::make_pair(value, bits_needed(value))); + } + + bit_stream bs; + for (std::vector<value_pair>::iterator i = values.begin(); + i != values.end(); ++i) + { + bs.write_uint(i->first, i->second); + } + bs.seek(0); + for (std::vector<value_pair>::iterator i = values.begin(); + i != values.end(); ++i) + { + ensure_equals("uint", bs.read_uint(i->second), i->first); + } + } +} diff --git a/tests/test.cpp b/tests/test.cpp new file mode 100644 index 0000000..bf49c38 --- /dev/null +++ b/tests/test.cpp @@ -0,0 +1,18 @@ +#include <tut.h> +#include <tut_reporter.h> +#include <iostream> + +namespace tut +{ + test_runner_singleton runner; +} + +int main() +{ + tut::reporter reporter; + tut::runner.get().set_callback(&reporter); + + tut::runner.get().run_tests(); + + return !reporter.all_ok(); +}
darka/blahnet
e5d7cfd7e8f99420dea7e2845fc49df8dbde3635
build currently broken; packet peer, client classes (in-development); reliable_layer will be replaced by server/client classes, deriving from link_common (not yet renamed)
diff --git a/src/client.hpp b/src/client.hpp new file mode 100644 index 0000000..2c5fc23 --- /dev/null +++ b/src/client.hpp @@ -0,0 +1,17 @@ +#ifndef UUID_D9717A39A7864EDC96BAA9C5A9A7E38C +#define UUID_D9717A39A7864EDC96BAA9C5A9A7E38C + + +struct client +{ + client(); + + ~client(); + +private: + + +}; + +#endif // UUID_D9717A39A7864EDC96BAA9C5A9A7E38C + diff --git a/src/link.hpp b/src/link.hpp index 29cb99b..417ee7b 100644 --- a/src/link.hpp +++ b/src/link.hpp @@ -1,36 +1,32 @@ #ifndef UUID_52DA523EF9CE4CF3A46629AAEC07E467 #define UUID_52DA523EF9CE4CF3A46629AAEC07E467 #include "bit_stream.hpp" #include "udp_socket.hpp" #include <boost/signal.hpp> +// TODO: rename to link_common struct link { enum disconnection_reason { timeout = 0, voluntary = 1 }; ~link(); //void host(unsigned short int port); //void connect(address const& addr); - void send(bit_stream const& data); + //void send(bit_stream const& data); - // TODO: how to cache the addresses? - boost::signal<void (address const&)> on_connect; - boost::signal<void (address const&, - disconnection_reason const&)> on_disconnect; - - boost::signal<void (address const&, bit_stream const&)> on_receive; protected: link(); //bool connected; //address addr; udp_socket sock; + static uint8 const protocol_version = 0; }; #endif // UUID_52DA523EF9CE4CF3A46629AAEC07E467 diff --git a/src/packet.cpp b/src/packet.cpp new file mode 100644 index 0000000..73f1825 --- /dev/null +++ b/src/packet.cpp @@ -0,0 +1,8 @@ +#include "packet.hpp" + +packet::packet(char const* msg, std::size_t msg_len, + uint8 peer_id, uint8 seq_num, + address const& addr) +{ + +} diff --git a/src/packet.hpp b/src/packet.hpp new file mode 100644 index 0000000..32f43ff --- /dev/null +++ b/src/packet.hpp @@ -0,0 +1,26 @@ +#ifndef UUID_75A46991F81648ED83D9A7E8D598BE9D +#define UUID_75A46991F81648ED83D9A7E8D598BE9D + +#include "types.hpp" + +struct packet +{ + packet(char const* msg, std::size_t msg_len, + uint8 peer_id, uint8 seq_num, + address const& addr); // message with a header + // TODO: ack packets should contain multiple acks + packet(uint8 peer_id, uint8 seq_num, + address const& addr); // ack packet + ~packet(); + + char* msg() { return msg; } + std::size_t msg_len() { msg_len_; } + address const& addr() { return addr_; } + +private: + char* msg_; + std::size_t msg_len_; + address const& addr_; +}; + +#endif // UUID_75A46991F81648ED83D9A7E8D598BE9D diff --git a/src/peer.cpp b/src/peer.cpp new file mode 100644 index 0000000..f50f85d --- /dev/null +++ b/src/peer.cpp @@ -0,0 +1,9 @@ +#include "peer.hpp" + +peer::peer(address const& addr) +: addr(addr) +, incoming_seq_number(0) +, outgoing_seq_number(0) +{ +} + diff --git a/src/peer.hpp b/src/peer.hpp new file mode 100644 index 0000000..880f5c0 --- /dev/null +++ b/src/peer.hpp @@ -0,0 +1,22 @@ +#ifndef UUID_166D7E8EF9514324B94DBBCCCF7FEDA8 +#define UUID_166D7E8EF9514324B94DBBCCCF7FEDA8 + +#include "address.hpp" +#include "types.hpp" + +struct peer +{ + peer(address const& addr); + + address const& addr() { return addr_; } + uint8 incoming_seq_number() { return incoming_seq_number_; } + uint8 outgoing_seq_number() { return outgoing_seq_number_; } + +private: + address addr_; + uint8 incoming_seq_number_; + uint8 outgoing_seq_number_; +}; + +#endif // UUID_166D7E8EF9514324B94DBBCCCF7FEDA8 + diff --git a/src/reliable_layer.cpp b/src/reliable_layer.cpp index a38c21f..4f1acc5 100644 --- a/src/reliable_layer.cpp +++ b/src/reliable_layer.cpp @@ -1,59 +1,72 @@ #include "reliable_layer.hpp" +#include <cassert> #include <cstring> reliable_layer::reliable_layer() : seq_num(0) , expecting(false) , expected_num(0) { sock.create(); sock.set_nonblocking(); } reliable_layer::~reliable_layer() { while (!packets.empty()) { - packet* current_packet = packets.front(); - delete[] current_packet->msg; - delete current_packet; - packets.pop(); + pop_top_packet(); } } -void reliable_layer::sendto(char const* msg, std::size_t msg_len, - address const& addr) -{ - // TODO: split the packet here? need to guard against overflow anyway - std::size_t prepared_msg_len = msg_len + 2; - char* prepared_msg = new char[prepared_msg_len]; - std::memcpy(prepared_msg + 2, msg, msg_len); - std::memset(prepared_msg, 0, 2); - - // attach header - // first 7 bits = protocol version - // TODO: (how else do we do this? on connection? look at q3 - prepared_msg[0] |= (protocol_version << 1); - // we're not sending an ack packet, so the 8th bit is 1 - prepared_msg[0] |= 1; - // attach sequence number - prepared_msg[1] |= seq_num; - // store in a queue? - packets.push(new packet(prepared_msg, prepared_msg_len, addr)); - seq_num += 1; -} - void reliable_layer::work() { - if (!packets.empty()) + // receive packets + // TODO: enforce default max packet size everywhere? + unsigned int const packet_size = 20; + char msg[packet_size]; + address addr; + int result = sock.recvfrom(msg, packet_size - 1, addr); + if (result != -1) + { + // TODO: should disconnect the client instead + assert((msg[0] >> 1) == protocol_version); + // is packet an ack? + if ((msg[0] & 0x1) == 0) + { + if (expecting && msg[1] == expected_num) + pop_top_packet(); + } + else + { + // send an ack + // TODO: pack many acks in one packet + } + + } + + if (packets.empty()) + { + expecting = false; + } + else { // send top packet packet* current_packet = packets.front(); + // TODO: error checking sock.sendto(current_packet->msg, current_packet->msg_len, current_packet->addr); + expecting = true; + expected_num = current_packet->msg[1]; + pop_top_packet(); + } + +} + +void reliable_layer::pop_top_packet() +{ + packet* current_packet = packets.front(); delete[] current_packet->msg; delete current_packet; packets.pop(); - } } - diff --git a/src/reliable_layer.hpp b/src/reliable_layer.hpp index f326373..1f1e654 100644 --- a/src/reliable_layer.hpp +++ b/src/reliable_layer.hpp @@ -1,43 +1,31 @@ #ifndef UUID_073328F7899A4DD0B86369768768AFE7 #define UUID_073328F7899A4DD0B86369768768AFE7 #include "udp_socket.hpp" #include "bit_stream.hpp" #include "types.hpp" #include <queue> #include <utility> struct reliable_layer { - explicit reliable_layer(); + reliable_layer(); ~reliable_layer(); void sendto(char const* msg, std::size_t msg_len, address const& addr); void work(); private: - struct packet - { - packet(char const* msg, std::size_t msg_len, - address const& addr) - : msg(msg) - , msg_len(msg_len) - , addr(addr) - { - } - char const* msg; - std::size_t msg_len; - address const& addr; - }; + void pop_top_packet(); // handles memory udp_socket sock; uint8 seq_num; // sequence number used in sent message header bool expecting; // if expecting ack packets uint8 expected_num; // sequence number we're waiting for std::queue<packet*> packets; static uint8 const protocol_version = 0; }; #endif // UUID_073328F7899A4DD0B86369768768AFE7 diff --git a/src/server.cpp b/src/server.cpp index 2c3bfa7..4a0b68e 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1,17 +1,86 @@ #include "server.hpp" server::server() +: expecting(false) { } void server::host(unsigned short int port) { sock.create(); sock.bind(port); } +void server::work() +{ + // receive packets + // TODO: enforce default max packet size everywhere? + // should go into link.hpp if so + unsigned int const packet_size = 20; + char msg[packet_size]; + address addr; + int result = sock.recvfrom(msg, packet_size - 1, addr); + if (result != -1) + { + // TODO: should disconnect the client instead + assert((msg[0] >> 1) == protocol_version); + // is packet an ack? + if ((msg[0] & 0x1) == 0) + { + if (expecting && msg[1] == expected_num) + pop_top_packet(); + } + else + { + // send an ack + // TODO: pack many acks in one packet + } + + } + + if (packets.empty()) + { + expecting = false; + } + else + { + // send top packet + packet* current_packet = packets.front(); + // TODO: error checking + sock.sendto(current_packet->msg, current_packet->msg_len, + current_packet->addr); + expecting = true; + expected_num = current_packet->msg[1]; + pop_top_packet(); + } + +} + void server::stop() { sock.close(); } +void server::sendto(char const* msg, std::size_t msg_len, + uint8 peer_id) +{ + // TODO: split the packet here? need to guard against overflow anyway + std::size_t prepared_msg_len = msg_len + 2; + char* prepared_msg = new char[prepared_msg_len]; + std::memcpy(prepared_msg + 2, msg, msg_len); + std::memset(prepared_msg, 0, 2); + + // attach header + // first 7 bits = protocol version + // TODO: (how else do we do this? on connection? look at q3 + prepared_msg[0] |= (protocol_version << 1); + // we're not sending an ack packet, so the 8th bit is 1 + prepared_msg[0] |= 1; + // attach sequence number + prepared_msg[1] |= seq_num; + // store in a queue? + packets.push(new packet(prepared_msg, prepared_msg_len, addr)); + seq_num += 1; +} + + diff --git a/src/server.hpp b/src/server.hpp index 4f5baf6..1ec1015 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -1,16 +1,31 @@ #ifndef UUID_A3C8588901A048B6B6FB438C5F31BBCF #define UUID_A3C8588901A048B6B6FB438C5F31BBCF #include "link.hpp" +#include "peer.hpp" +#include <map> struct server : public link { server(); void host(unsigned short int port); + void work(); void stop(); // does nothing if not hosting -//private: + + void sendto(char const* msg, std::size_t msg_len, + uint8 peer_id); + + // TODO: how to cache the addresses? ??? + boost::signal<void (address const&)> on_connect; + boost::signal<void (address const&, + disconnection_reason const&)> on_disconnect; + + boost::signal<void (address const&, bit_stream const&)> on_receive; +private: + std::map<uint8, peer> peers; // unique peer id => peer + bool expecting; }; #endif // UUID_A3C8588901A048B6B6FB438C5F31BBCF
darka/blahnet
86d1febf458b9d0724cc57597c87338059312b76
moved out winsock (de)initialization to socket_common
diff --git a/src/socket_common.cpp b/src/socket_common.cpp index aac12d8..e2fd389 100644 --- a/src/socket_common.cpp +++ b/src/socket_common.cpp @@ -1,88 +1,99 @@ #include "socket_common_func.hpp" // includes winsock.h #include "socket_common.hpp" #ifndef BLAHNET_WIN32 #include <unistd.h> #endif // BLAHNET_WIN32 socket_common::socket_common() : data(new socket_data()) { } socket_common::socket_common(socket_common const& other) : data(other.data) { ++data->count; } socket_common::~socket_common() { --data->count; if (data->count == 0) { delete data; } } socket_common& socket_common::operator=(socket_common const& other) { socket_data* const old = data; data = other.data; ++data->count; if (--old->count == 0) delete old; return *this; } #ifdef BLAHNET_WIN32 +void init_wsock() +{ + WSADATA wsa_data; + WSAStartup(MAKEWORD(2, 2), &wsa_data); +} + +void quit_wsock() +{ + WSACleanup(); +} + int socket_common::socket_data::wsock_total_count = 0; #endif //BLAHNET_WIN32 socket_common::socket_data::socket_data() : count(1) , needs_closing(false) { #ifdef BLAHNET_WIN32 if (wsock_total_count == 0) { init_wsock(); } wsock_total_count += 1; #endif // BLAHNET_WIN32 } socket_common::socket_data::~socket_data() { close(); #ifdef BLAHNET_WIN32 wsock_total_count -= 1; if (wsock_total_count == 0) { quit_wsock(); } #endif // BLAHNET_WIN32 } void socket_common::socket_data::set_needs_closing() { needs_closing = true; } void socket_common::socket_data::close() { if (needs_closing) { #ifdef BLAHNET_WIN32 closesocket((SOCKET)wsock); #else ::close(psock); #endif // BLAHNET_WIN32 needs_closing = false; } } diff --git a/src/socket_common_func.cpp b/src/socket_common_func.cpp index 5d951a2..ec06379 100644 --- a/src/socket_common_func.cpp +++ b/src/socket_common_func.cpp @@ -1,29 +1,18 @@ #include "socket_common_func.hpp" #include "socket_common.hpp" #ifdef BLAHNET_WIN32 -void init_wsock() -{ - WSADATA wsa_data; - WSAStartup(MAKEWORD(2, 2), &wsa_data); -} - -void quit_wsock() -{ - WSACleanup(); -} - SOCKET get_descriptor(socket_common const& socket) { return (SOCKET)socket.data->wsock; } #else int get_descriptor(socket_common const& socket) { return socket.data->psock; } #endif // BLAHNET_WIN32 diff --git a/src/socket_common_func.hpp b/src/socket_common_func.hpp index 659117c..e40e34f 100644 --- a/src/socket_common_func.hpp +++ b/src/socket_common_func.hpp @@ -1,22 +1,20 @@ #ifndef UUID_9324CDC8D22248E98D42A8CC941A5635 #define UUID_9324CDC8D22248E98D42A8CC941A5635 struct socket_common; #ifdef BLAHNET_WIN32 #include <winsock.h> -void init_wsock(); -void quit_wsock(); SOCKET get_descriptor(socket_common const& socket); #else int get_descriptor(socket_common const& socket); #endif // BLAHNET_WIN32 #endif // UUID_9324CDC8D22248E98D42A8CC941A5635
darka/blahnet
19b7586b8ab0333ea06a9a9121457b3ce3047679
reliable_layer in-development class
diff --git a/client/client.cpp b/client/client.cpp index 1ed7604..5c228d5 100644 --- a/client/client.cpp +++ b/client/client.cpp @@ -1,9 +1,9 @@ -#include "udp_socket.hpp" +#include "reliable_layer.hpp" int main() { - udp_socket sock; - sock.create(); + reliable_layer rel_link; address addr(23232, "127.0.0.1"); char msg[] = "lol wat"; - sock.sendto(msg, strlen(msg), addr); + rel_link.sendto(msg, strlen(msg), addr); + rel_link.work(); } diff --git a/src/reliable_layer.cpp b/src/reliable_layer.cpp new file mode 100644 index 0000000..a38c21f --- /dev/null +++ b/src/reliable_layer.cpp @@ -0,0 +1,59 @@ +#include "reliable_layer.hpp" +#include <cstring> + +reliable_layer::reliable_layer() +: seq_num(0) +, expecting(false) +, expected_num(0) +{ + sock.create(); + sock.set_nonblocking(); +} + +reliable_layer::~reliable_layer() +{ + while (!packets.empty()) + { + packet* current_packet = packets.front(); + delete[] current_packet->msg; + delete current_packet; + packets.pop(); + } +} + +void reliable_layer::sendto(char const* msg, std::size_t msg_len, + address const& addr) +{ + // TODO: split the packet here? need to guard against overflow anyway + std::size_t prepared_msg_len = msg_len + 2; + char* prepared_msg = new char[prepared_msg_len]; + std::memcpy(prepared_msg + 2, msg, msg_len); + std::memset(prepared_msg, 0, 2); + + // attach header + // first 7 bits = protocol version + // TODO: (how else do we do this? on connection? look at q3 + prepared_msg[0] |= (protocol_version << 1); + // we're not sending an ack packet, so the 8th bit is 1 + prepared_msg[0] |= 1; + // attach sequence number + prepared_msg[1] |= seq_num; + // store in a queue? + packets.push(new packet(prepared_msg, prepared_msg_len, addr)); + seq_num += 1; +} + +void reliable_layer::work() +{ + if (!packets.empty()) + { + // send top packet + packet* current_packet = packets.front(); + sock.sendto(current_packet->msg, current_packet->msg_len, + current_packet->addr); + delete[] current_packet->msg; + delete current_packet; + packets.pop(); + } +} + diff --git a/src/reliable_layer.hpp b/src/reliable_layer.hpp new file mode 100644 index 0000000..f326373 --- /dev/null +++ b/src/reliable_layer.hpp @@ -0,0 +1,43 @@ +#ifndef UUID_073328F7899A4DD0B86369768768AFE7 +#define UUID_073328F7899A4DD0B86369768768AFE7 + +#include "udp_socket.hpp" +#include "bit_stream.hpp" +#include "types.hpp" +#include <queue> +#include <utility> + +struct reliable_layer +{ + explicit reliable_layer(); + ~reliable_layer(); + void sendto(char const* msg, std::size_t msg_len, + address const& addr); + void work(); + +private: + + struct packet + { + packet(char const* msg, std::size_t msg_len, + address const& addr) + : msg(msg) + , msg_len(msg_len) + , addr(addr) + { + } + char const* msg; + std::size_t msg_len; + address const& addr; + }; + + udp_socket sock; + uint8 seq_num; // sequence number used in sent message header + bool expecting; // if expecting ack packets + uint8 expected_num; // sequence number we're waiting for + std::queue<packet*> packets; + static uint8 const protocol_version = 0; +}; + +#endif // UUID_073328F7899A4DD0B86369768768AFE7 + diff --git a/src/udp_socket.cpp b/src/udp_socket.cpp index fba2fb7..7b855c8 100644 --- a/src/udp_socket.cpp +++ b/src/udp_socket.cpp @@ -1,79 +1,77 @@ #include "socket_common_func.hpp" // includes winsock.h #include "udp_socket.hpp" #ifndef BLAHNET_WIN32 #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #endif // BLAHNET_WIN32 udp_socket::udp_socket() { } int udp_socket::create() { - // TODO: fix this ugliness + int result; #ifdef BLAHNET_WIN32 - data->wsock = ::socket(PF_INET, SOCK_DGRAM, 0); - if (data->wsock == -1) - return -1; + result = data->wsock = ::socket(PF_INET, SOCK_DGRAM, 0); #else - data->psock = ::socket(PF_INET, SOCK_DGRAM, 0); - if (data->psock == -1) - return -1; + result = data->psock = ::socket(PF_INET, SOCK_DGRAM, 0); #endif // BLAHNET_WIN32 + if (result == -1) + return -1; data->set_needs_closing(); return 0; } void udp_socket::set_nonblocking() { #ifdef BLAHNET_WIN32 u_long non_blocking = 1; ioctlsocket(get_descriptor(*this), FIONBIO, &non_blocking); #else fcntl(get_descriptor(*this), F_SETFL, O_NONBLOCK); #endif // BLAHNET_WIN32 } /* TODO: real error handling */ int udp_socket::bind(unsigned short int port) { address addr(port); return ::bind(get_descriptor(*this), reinterpret_cast<sockaddr*>(addr.data()), sizeof(sockaddr)); } int udp_socket::sendto(char const* msg, std::size_t len, address const& addr) { return ::sendto(get_descriptor(*this), msg, len, 0, reinterpret_cast<sockaddr const*>(addr.data()), sizeof(sockaddr)); } int udp_socket::recvfrom(char* msg, std::size_t len, address& addr) { #ifdef BLAHNET_WIN32 int from_len = sizeof(sockaddr); #else socklen_t from_len = sizeof(sockaddr); #endif // BLAHNET_WIN32 return ::recvfrom(get_descriptor(*this), msg, len, 0, reinterpret_cast<sockaddr*>(addr.data()), &from_len); } void udp_socket::close() { data->close(); }
darka/blahnet
1b20819fd6ab03ad807e2ae820bed5159737f88b
link and server in-development classes
diff --git a/src/link.cpp b/src/link.cpp new file mode 100644 index 0000000..e3989e9 --- /dev/null +++ b/src/link.cpp @@ -0,0 +1,13 @@ +#include "link.hpp" + +// TODO: error handling with exceptions + +link::link() +{ +} + +link::~link() +{ + sock.close(); +} + diff --git a/src/connection.hpp b/src/link.hpp similarity index 79% rename from src/connection.hpp rename to src/link.hpp index 42a79fa..29cb99b 100644 --- a/src/connection.hpp +++ b/src/link.hpp @@ -1,35 +1,36 @@ #ifndef UUID_52DA523EF9CE4CF3A46629AAEC07E467 #define UUID_52DA523EF9CE4CF3A46629AAEC07E467 #include "bit_stream.hpp" #include "udp_socket.hpp" #include <boost/signal.hpp> -struct connection +struct link { enum disconnection_reason { timeout = 0, voluntary = 1 - }; - connection(address const& addr); - ~connection(); + ~link(); + //void host(unsigned short int port); + //void connect(address const& addr); + void send(bit_stream const& data); - void disconnect(); // TODO: how to cache the addresses? boost::signal<void (address const&)> on_connect; boost::signal<void (address const&, disconnection_reason const&)> on_disconnect; boost::signal<void (address const&, bit_stream const&)> on_receive; - -private: - address addr; +protected: + link(); + //bool connected; + //address addr; udp_socket sock; }; #endif // UUID_52DA523EF9CE4CF3A46629AAEC07E467 diff --git a/src/server.cpp b/src/server.cpp new file mode 100644 index 0000000..2c3bfa7 --- /dev/null +++ b/src/server.cpp @@ -0,0 +1,17 @@ +#include "server.hpp" + +server::server() +{ +} + +void server::host(unsigned short int port) +{ + sock.create(); + sock.bind(port); +} + +void server::stop() +{ + sock.close(); +} + diff --git a/src/server.hpp b/src/server.hpp new file mode 100644 index 0000000..4f5baf6 --- /dev/null +++ b/src/server.hpp @@ -0,0 +1,16 @@ +#ifndef UUID_A3C8588901A048B6B6FB438C5F31BBCF +#define UUID_A3C8588901A048B6B6FB438C5F31BBCF + +#include "link.hpp" + +struct server : public link +{ + server(); + void host(unsigned short int port); + void stop(); // does nothing if not hosting +//private: + +}; + +#endif // UUID_A3C8588901A048B6B6FB438C5F31BBCF +
darka/blahnet
6df93a76a6991cf39b00b7a1b19d9f6285bdacf1
connection class header (probably need to rename it)
diff --git a/src/connection.hpp b/src/connection.hpp new file mode 100644 index 0000000..42a79fa --- /dev/null +++ b/src/connection.hpp @@ -0,0 +1,35 @@ +#ifndef UUID_52DA523EF9CE4CF3A46629AAEC07E467 +#define UUID_52DA523EF9CE4CF3A46629AAEC07E467 + +#include "bit_stream.hpp" +#include "udp_socket.hpp" +#include <boost/signal.hpp> + +struct connection +{ + enum disconnection_reason + { + timeout = 0, + voluntary = 1 + + }; + + connection(address const& addr); + ~connection(); + + void send(bit_stream const& data); + void disconnect(); + + // TODO: how to cache the addresses? + boost::signal<void (address const&)> on_connect; + boost::signal<void (address const&, + disconnection_reason const&)> on_disconnect; + + boost::signal<void (address const&, bit_stream const&)> on_receive; + +private: + address addr; + udp_socket sock; +}; +#endif // UUID_52DA523EF9CE4CF3A46629AAEC07E467 +
darka/blahnet
0f5a18d051df29e34c222448baeab2c945bd061f
replaced SOCKET_DESCRIPTOR() with a get_descriptor() function
diff --git a/src/socket_common.cpp b/src/socket_common.cpp index 3b14a9e..aac12d8 100644 --- a/src/socket_common.cpp +++ b/src/socket_common.cpp @@ -1,99 +1,88 @@ +#include "socket_common_func.hpp" // includes winsock.h #include "socket_common.hpp" -#ifdef BLAHNET_WIN32 -#include <winsock.h> -#else +#ifndef BLAHNET_WIN32 #include <unistd.h> #endif // BLAHNET_WIN32 socket_common::socket_common() : data(new socket_data()) { } socket_common::socket_common(socket_common const& other) : data(other.data) { ++data->count; } socket_common::~socket_common() { --data->count; if (data->count == 0) { delete data; } } socket_common& socket_common::operator=(socket_common const& other) { socket_data* const old = data; data = other.data; ++data->count; if (--old->count == 0) delete old; return *this; } #ifdef BLAHNET_WIN32 int socket_common::socket_data::wsock_total_count = 0; -void init_wsock() -{ - WSADATA wsa_data; - WSAStartup(MAKEWORD(2, 2), &wsa_data); -} - -void quit_wsock() -{ - WSACleanup(); -} #endif //BLAHNET_WIN32 socket_common::socket_data::socket_data() : count(1) , needs_closing(false) { #ifdef BLAHNET_WIN32 if (wsock_total_count == 0) { init_wsock(); } wsock_total_count += 1; #endif // BLAHNET_WIN32 } socket_common::socket_data::~socket_data() { close(); #ifdef BLAHNET_WIN32 wsock_total_count -= 1; if (wsock_total_count == 0) { quit_wsock(); } #endif // BLAHNET_WIN32 } void socket_common::socket_data::set_needs_closing() { needs_closing = true; } void socket_common::socket_data::close() { if (needs_closing) { #ifdef BLAHNET_WIN32 closesocket((SOCKET)wsock); #else ::close(psock); #endif // BLAHNET_WIN32 needs_closing = false; } } diff --git a/src/socket_common.hpp b/src/socket_common.hpp index 002c977..ae3d6b9 100644 --- a/src/socket_common.hpp +++ b/src/socket_common.hpp @@ -1,36 +1,46 @@ #ifndef UUID_6091A81C00E14F7F855C382F4C918DA5 #define UUID_6091A81C00E14F7F855C382F4C918DA5 +struct udp_socket; +struct tcp_socket; + struct socket_common { - socket_common(); - socket_common(socket_common const& other); - ~socket_common(); - socket_common& operator=(socket_common const& other); - -protected: struct socket_data { + friend struct socket_common; + friend struct udp_socket; + friend struct tcp_socket; + socket_data(); ~socket_data(); socket_data(socket_data const& other); socket_data& operator=(socket_data const& other); - void set_needs_closing(); - void close(); + union { void* wsock; // winsock socket int psock; // BSD POSIX socket }; - int count; + private: + void set_needs_closing(); + void close(); + + int count; bool needs_closing; #ifdef BLAHNET_WIN32 static int wsock_total_count; #endif // BLAHNET_WIN32 }; + + socket_common(); + socket_common(socket_common const& other); + ~socket_common(); + socket_common& operator=(socket_common const& other); + socket_data* data; }; #endif // UUID_6091A81C00E14F7F855C382F4C918DA5 diff --git a/src/socket_common_func.cpp b/src/socket_common_func.cpp new file mode 100644 index 0000000..5d951a2 --- /dev/null +++ b/src/socket_common_func.cpp @@ -0,0 +1,29 @@ +#include "socket_common_func.hpp" +#include "socket_common.hpp" + +#ifdef BLAHNET_WIN32 + +void init_wsock() +{ + WSADATA wsa_data; + WSAStartup(MAKEWORD(2, 2), &wsa_data); +} + +void quit_wsock() +{ + WSACleanup(); +} + +SOCKET get_descriptor(socket_common const& socket) +{ + return (SOCKET)socket.data->wsock; +} + +#else + +int get_descriptor(socket_common const& socket) +{ + return socket.data->psock; +} + +#endif // BLAHNET_WIN32 diff --git a/src/socket_common_func.hpp b/src/socket_common_func.hpp new file mode 100644 index 0000000..659117c --- /dev/null +++ b/src/socket_common_func.hpp @@ -0,0 +1,22 @@ +#ifndef UUID_9324CDC8D22248E98D42A8CC941A5635 +#define UUID_9324CDC8D22248E98D42A8CC941A5635 + +struct socket_common; + +#ifdef BLAHNET_WIN32 + +#include <winsock.h> + +void init_wsock(); +void quit_wsock(); +SOCKET get_descriptor(socket_common const& socket); + +#else + +int get_descriptor(socket_common const& socket); + +#endif // BLAHNET_WIN32 + +#endif // UUID_9324CDC8D22248E98D42A8CC941A5635 + + diff --git a/src/udp_socket.cpp b/src/udp_socket.cpp index 3d9735b..fba2fb7 100644 --- a/src/udp_socket.cpp +++ b/src/udp_socket.cpp @@ -1,80 +1,79 @@ +#include "socket_common_func.hpp" // includes winsock.h #include "udp_socket.hpp" -#ifdef BLAHNET_WIN32 - -#include <winsock.h> - -#define SOCKET_DESCRIPTOR() (SOCKET)data->wsock - -#else +#ifndef BLAHNET_WIN32 #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> -#define SOCKET_DESCRIPTOR() data->psock - #endif // BLAHNET_WIN32 udp_socket::udp_socket() { } int udp_socket::create() { - // TODO: fix this + // TODO: fix this ugliness +#ifdef BLAHNET_WIN32 + data->wsock = ::socket(PF_INET, SOCK_DGRAM, 0); + if (data->wsock == -1) + return -1; +#else data->psock = ::socket(PF_INET, SOCK_DGRAM, 0); if (data->psock == -1) return -1; +#endif // BLAHNET_WIN32 data->set_needs_closing(); return 0; } void udp_socket::set_nonblocking() { #ifdef BLAHNET_WIN32 u_long non_blocking = 1; - ioctlsocket(SOCKET_DESCRIPTOR(), FIONBIO, &non_blocking); + ioctlsocket(get_descriptor(*this), FIONBIO, &non_blocking); #else - fcntl(SOCKET_DESCRIPTOR(), F_SETFL, O_NONBLOCK); + fcntl(get_descriptor(*this), F_SETFL, O_NONBLOCK); #endif // BLAHNET_WIN32 } /* TODO: real error handling */ int udp_socket::bind(unsigned short int port) { address addr(port); - return ::bind(SOCKET_DESCRIPTOR(), + return ::bind(get_descriptor(*this), reinterpret_cast<sockaddr*>(addr.data()), sizeof(sockaddr)); } int udp_socket::sendto(char const* msg, std::size_t len, address const& addr) { - return ::sendto(SOCKET_DESCRIPTOR(), msg, len, 0, + return ::sendto(get_descriptor(*this), msg, len, 0, reinterpret_cast<sockaddr const*>(addr.data()), sizeof(sockaddr)); } int udp_socket::recvfrom(char* msg, std::size_t len, address& addr) { #ifdef BLAHNET_WIN32 int from_len = sizeof(sockaddr); #else socklen_t from_len = sizeof(sockaddr); #endif // BLAHNET_WIN32 - return ::recvfrom(SOCKET_DESCRIPTOR(), msg, len, 0, + return ::recvfrom(get_descriptor(*this), msg, len, 0, reinterpret_cast<sockaddr*>(addr.data()), &from_len); } void udp_socket::close() { data->close(); }
darka/blahnet
5493a9c47f563cf5a8e245224557b2abd694c883
crappy portable SOCKET_DESCRIPTOR define; non-blocking sockets
diff --git a/src/udp_socket.cpp b/src/udp_socket.cpp index 6f74884..3d9735b 100644 --- a/src/udp_socket.cpp +++ b/src/udp_socket.cpp @@ -1,60 +1,80 @@ #include "udp_socket.hpp" #ifdef BLAHNET_WIN32 + #include <winsock.h> + +#define SOCKET_DESCRIPTOR() (SOCKET)data->wsock + #else + #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> +#include <fcntl.h> + +#define SOCKET_DESCRIPTOR() data->psock + #endif // BLAHNET_WIN32 udp_socket::udp_socket() { } int udp_socket::create() { + // TODO: fix this data->psock = ::socket(PF_INET, SOCK_DGRAM, 0); if (data->psock == -1) return -1; data->set_needs_closing(); return 0; } +void udp_socket::set_nonblocking() +{ +#ifdef BLAHNET_WIN32 + u_long non_blocking = 1; + ioctlsocket(SOCKET_DESCRIPTOR(), FIONBIO, &non_blocking); +#else + fcntl(SOCKET_DESCRIPTOR(), F_SETFL, O_NONBLOCK); +#endif // BLAHNET_WIN32 +} + /* TODO: real error handling */ int udp_socket::bind(unsigned short int port) { address addr(port); - return ::bind(data->psock, + return ::bind(SOCKET_DESCRIPTOR(), reinterpret_cast<sockaddr*>(addr.data()), sizeof(sockaddr)); } int udp_socket::sendto(char const* msg, std::size_t len, address const& addr) { - return ::sendto(data->psock, msg, len, 0, + return ::sendto(SOCKET_DESCRIPTOR(), msg, len, 0, reinterpret_cast<sockaddr const*>(addr.data()), sizeof(sockaddr)); } int udp_socket::recvfrom(char* msg, std::size_t len, address& addr) { #ifdef BLAHNET_WIN32 int from_len = sizeof(sockaddr); #else socklen_t from_len = sizeof(sockaddr); -#endif - return ::recvfrom(data->psock, msg, len, 0, +#endif // BLAHNET_WIN32 + return ::recvfrom(SOCKET_DESCRIPTOR(), msg, len, 0, reinterpret_cast<sockaddr*>(addr.data()), &from_len); } void udp_socket::close() { data->close(); } diff --git a/src/udp_socket.hpp b/src/udp_socket.hpp index c49a6c2..9361227 100644 --- a/src/udp_socket.hpp +++ b/src/udp_socket.hpp @@ -1,19 +1,20 @@ #ifndef UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 #define UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 #include "socket_common.hpp" #include "address.hpp" #include <cstring> struct udp_socket : public socket_common { udp_socket(); int create(); + void set_nonblocking(); int bind(unsigned short int port); int sendto(char const* msg, std::size_t len, address const& addr); int recvfrom(char* msg, std::size_t len, address& addr); void close(); }; #endif // UUID_96F8FCADA2CD4A1EAC27C1575447E3A7
darka/blahnet
605eee7dc8ac9ec122f295c2ed9fc8943c2eef46
compile on windows
diff --git a/CMakeLists.txt b/CMakeLists.txt index 7870bb9..648fb39 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,17 +1,30 @@ cmake_minimum_required(VERSION 2.4) project(NetNet) -set(CMAKE_CXX_FLAGS "-std=c++98 -Wall -Wextra -pedantic -ggdb3") + include_directories(src) file(GLOB main_sources src/*.cpp) file(GLOB server_sources server/*.cpp) file(GLOB client_sources client/*.cpp) + +if(WIN32) + add_definitions(-DBLAHNET_WIN32) +endif(WIN32) + +if(UNIX) + set(CMAKE_CXX_FLAGS "-std=c++98 -Wall -Wextra -pedantic -ggdb3") +endif(UNIX) + add_library(netnet STATIC ${main_sources}) # for testing add_executable(netnet-server ${server_sources}) add_executable(netnet-client ${client_sources}) -target_link_libraries(netnet-server netnet) -target_link_libraries(netnet-client netnet) - +if(WIN32) + target_link_libraries(netnet-server netnet wsock32) + target_link_libraries(netnet-client netnet wsock32) +else(WIN32) + target_link_libraries(netnet-server netnet) + target_link_libraries(netnet-client netnet) +endif(WIN32) diff --git a/src/address.cpp b/src/address.cpp index fcfb85b..e287c3e 100644 --- a/src/address.cpp +++ b/src/address.cpp @@ -1,38 +1,44 @@ #include "address.hpp" + +#ifdef BLAHNET_WIN32 +#include <winsock2.h> +#else #include <netinet/in.h> #include <arpa/inet.h> +#endif // BLAHNET_WIN32 + #include <cstring> void zero_pad(sockaddr_in& data) { std::memset(data.sin_zero, '\0', sizeof(data.sin_zero)); } address::address() : data_(new sockaddr_in) { } address::address(unsigned short int port) : data_(new sockaddr_in) { data_->sin_family = AF_INET; data_->sin_port = htons(port); data_->sin_addr.s_addr = INADDR_ANY; zero_pad(*data_); } address::address(unsigned short int port, char const* ip) : data_(new sockaddr_in) { data_->sin_family = AF_INET; data_->sin_port = htons(port); - inet_aton(ip, &(data_->sin_addr)); + data_->sin_addr.s_addr = inet_addr(ip); zero_pad(*data_); } address::~address() { delete data_; } diff --git a/src/socket_common.cpp b/src/socket_common.cpp index 4b2bfa9..3b14a9e 100644 --- a/src/socket_common.cpp +++ b/src/socket_common.cpp @@ -1,94 +1,99 @@ #include "socket_common.hpp" + +#ifdef BLAHNET_WIN32 +#include <winsock.h> +#else #include <unistd.h> +#endif // BLAHNET_WIN32 socket_common::socket_common() : data(new socket_data()) { } socket_common::socket_common(socket_common const& other) : data(other.data) { ++data->count; } socket_common::~socket_common() { --data->count; if (data->count == 0) { delete data; } } socket_common& socket_common::operator=(socket_common const& other) { socket_data* const old = data; data = other.data; ++data->count; if (--old->count == 0) delete old; return *this; } -#if BLAHNET_WIN32==1 +#ifdef BLAHNET_WIN32 int socket_common::socket_data::wsock_total_count = 0; void init_wsock() { WSADATA wsa_data; WSAStartup(MAKEWORD(2, 2), &wsa_data); } void quit_wsock() { WSACleanup(); } -#endif +#endif //BLAHNET_WIN32 socket_common::socket_data::socket_data() : count(1) , needs_closing(false) { -#if BLAHNET_WIN32==1 +#ifdef BLAHNET_WIN32 if (wsock_total_count == 0) { init_wsock(); } wsock_total_count += 1; -#endif +#endif // BLAHNET_WIN32 } socket_common::socket_data::~socket_data() { close(); -#if BLAHNET_WIN32==1 +#ifdef BLAHNET_WIN32 wsock_total_count -= 1; if (wsock_total_count == 0) { quit_wsock(); } -#endif +#endif // BLAHNET_WIN32 } void socket_common::socket_data::set_needs_closing() { needs_closing = true; } void socket_common::socket_data::close() { if (needs_closing) { -#if BLAHNET_WIN32==1 +#ifdef BLAHNET_WIN32 closesocket((SOCKET)wsock); #else ::close(psock); -#endif +#endif // BLAHNET_WIN32 needs_closing = false; } } diff --git a/src/socket_common.hpp b/src/socket_common.hpp index 21acc9a..002c977 100644 --- a/src/socket_common.hpp +++ b/src/socket_common.hpp @@ -1,36 +1,36 @@ #ifndef UUID_6091A81C00E14F7F855C382F4C918DA5 #define UUID_6091A81C00E14F7F855C382F4C918DA5 struct socket_common { socket_common(); socket_common(socket_common const& other); ~socket_common(); socket_common& operator=(socket_common const& other); protected: struct socket_data { socket_data(); ~socket_data(); socket_data(socket_data const& other); socket_data& operator=(socket_data const& other); void set_needs_closing(); void close(); union { void* wsock; // winsock socket int psock; // BSD POSIX socket }; int count; private: bool needs_closing; -#if BLAHNET_WIN32==1 +#ifdef BLAHNET_WIN32 static int wsock_total_count; -#endif +#endif // BLAHNET_WIN32 }; socket_data* data; }; #endif // UUID_6091A81C00E14F7F855C382F4C918DA5 diff --git a/src/udp_socket.cpp b/src/udp_socket.cpp index 6a7b65a..6f74884 100644 --- a/src/udp_socket.cpp +++ b/src/udp_socket.cpp @@ -1,51 +1,60 @@ #include "udp_socket.hpp" + +#ifdef BLAHNET_WIN32 +#include <winsock.h> +#else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> +#endif // BLAHNET_WIN32 udp_socket::udp_socket() { } int udp_socket::create() { data->psock = ::socket(PF_INET, SOCK_DGRAM, 0); if (data->psock == -1) return -1; data->set_needs_closing(); return 0; } /* TODO: real error handling */ int udp_socket::bind(unsigned short int port) { address addr(port); return ::bind(data->psock, reinterpret_cast<sockaddr*>(addr.data()), sizeof(sockaddr)); } -int udp_socket::sendto(void const* msg, std::size_t len, +int udp_socket::sendto(char const* msg, std::size_t len, address const& addr) { return ::sendto(data->psock, msg, len, 0, reinterpret_cast<sockaddr const*>(addr.data()), sizeof(sockaddr)); } -int udp_socket::recvfrom(void* msg, std::size_t len, address& addr) +int udp_socket::recvfrom(char* msg, std::size_t len, address& addr) { +#ifdef BLAHNET_WIN32 + int from_len = sizeof(sockaddr); +#else socklen_t from_len = sizeof(sockaddr); +#endif return ::recvfrom(data->psock, msg, len, 0, reinterpret_cast<sockaddr*>(addr.data()), &from_len); } void udp_socket::close() { data->close(); } diff --git a/src/udp_socket.hpp b/src/udp_socket.hpp index b42489a..c49a6c2 100644 --- a/src/udp_socket.hpp +++ b/src/udp_socket.hpp @@ -1,19 +1,19 @@ #ifndef UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 #define UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 #include "socket_common.hpp" #include "address.hpp" #include <cstring> struct udp_socket : public socket_common { udp_socket(); int create(); int bind(unsigned short int port); - int sendto(void const* msg, std::size_t len, address const& addr); - int recvfrom(void* msg, std::size_t len, address& addr); + int sendto(char const* msg, std::size_t len, address const& addr); + int recvfrom(char* msg, std::size_t len, address& addr); void close(); }; #endif // UUID_96F8FCADA2CD4A1EAC27C1575447E3A7
darka/blahnet
6ea882416d17fbb148a792ed4dbeb447a97af6cc
simple udp sockets, lots of restructuring
diff --git a/client/client.cpp b/client/client.cpp index 5047a34..1ed7604 100644 --- a/client/client.cpp +++ b/client/client.cpp @@ -1,3 +1,9 @@ +#include "udp_socket.hpp" int main() { + udp_socket sock; + sock.create(); + address addr(23232, "127.0.0.1"); + char msg[] = "lol wat"; + sock.sendto(msg, strlen(msg), addr); } diff --git a/server/server.cpp b/server/server.cpp index 5047a34..bd4f4cb 100644 --- a/server/server.cpp +++ b/server/server.cpp @@ -1,3 +1,13 @@ +#include "udp_socket.hpp" +#include <iostream> + int main() { + udp_socket sock; + sock.create(); + sock.bind(23232); + address receiver_addr; + char buf[100]; + int bytes = sock.recvfrom(buf, 99, receiver_addr); + std::cout << bytes << "\n"; } diff --git a/src/address.cpp b/src/address.cpp index 9359362..fcfb85b 100644 --- a/src/address.cpp +++ b/src/address.cpp @@ -1,25 +1,38 @@ #include "address.hpp" +#include <netinet/in.h> +#include <arpa/inet.h> +#include <cstring> + +void zero_pad(sockaddr_in& data) +{ + std::memset(data.sin_zero, '\0', sizeof(data.sin_zero)); +} address::address() -: ip_(0) -, port_(0) +: data_(new sockaddr_in) { } address::address(unsigned short int port) -: ip_(0) -, port_(port) +: data_(new sockaddr_in) { + data_->sin_family = AF_INET; + data_->sin_port = htons(port); + data_->sin_addr.s_addr = INADDR_ANY; + zero_pad(*data_); } -address::address(unsigned short int port, const char* ip) -: ip_(ip) -, port_(port) +address::address(unsigned short int port, char const* ip) +: data_(new sockaddr_in) { + data_->sin_family = AF_INET; + data_->sin_port = htons(port); + inet_aton(ip, &(data_->sin_addr)); + zero_pad(*data_); } -#if 0 -void address::zeroPad() + +address::~address() { - std::memset(data.sin_zero, '\0', sizeof(data.sin_zero)); + delete data_; } -#endif + diff --git a/src/address.hpp b/src/address.hpp index 46d13f4..98335aa 100644 --- a/src/address.hpp +++ b/src/address.hpp @@ -1,18 +1,28 @@ #ifndef UUID_8B00007D6BED43B1AF63C689D9D35D78 #define UUID_8B00007D6BED43B1AF63C689D9D35D78 +struct sockaddr_in; + +/* TODO: implement copy constructor and operator= */ struct address { address(); /* uses host's ip address and picks a port automatically */ - address(unsigned short int port); /* uses host's ip address and uses given port */ - address(unsigned short int port, const char* ip); /* uses given ip and port */ - - unsigned short int port() const { return port_; } - const char* ip() const { return ip_; } + address(unsigned short int port); /* uses host's ip address and + uses given port */ + address(unsigned short int port, char const* ip); /* uses given ip + and port */ + address(address const& other); + ~address(); + + address& operator=(address const& other); + + /*unsigned short int port() const; + const char* ip() const;*/ + sockaddr_in const* data() const { return data_; } + sockaddr_in* data() { return data_; } private: - const char* ip_; - unsigned short int port_; + sockaddr_in* data_; }; #endif // UUID_8B00007D6BED43B1AF63C689D9D35D78 diff --git a/src/socket_common.cpp b/src/socket_common.cpp new file mode 100644 index 0000000..4b2bfa9 --- /dev/null +++ b/src/socket_common.cpp @@ -0,0 +1,94 @@ +#include "socket_common.hpp" +#include <unistd.h> + +socket_common::socket_common() +: data(new socket_data()) +{ +} + +socket_common::socket_common(socket_common const& other) +: data(other.data) +{ + ++data->count; +} + +socket_common::~socket_common() +{ + --data->count; + if (data->count == 0) + { + delete data; + } +} + +socket_common& socket_common::operator=(socket_common const& other) +{ + socket_data* const old = data; + data = other.data; + ++data->count; + if (--old->count == 0) + delete old; + return *this; + +} + +#if BLAHNET_WIN32==1 + +int socket_common::socket_data::wsock_total_count = 0; + +void init_wsock() +{ + WSADATA wsa_data; + WSAStartup(MAKEWORD(2, 2), &wsa_data); +} + +void quit_wsock() +{ + WSACleanup(); +} +#endif + +socket_common::socket_data::socket_data() +: count(1) +, needs_closing(false) +{ +#if BLAHNET_WIN32==1 + if (wsock_total_count == 0) + { + init_wsock(); + } + wsock_total_count += 1; +#endif +} + +socket_common::socket_data::~socket_data() +{ + close(); +#if BLAHNET_WIN32==1 + wsock_total_count -= 1; + if (wsock_total_count == 0) + { + quit_wsock(); + } +#endif +} + +void socket_common::socket_data::set_needs_closing() +{ + needs_closing = true; +} + +void socket_common::socket_data::close() +{ + if (needs_closing) + { +#if BLAHNET_WIN32==1 + closesocket((SOCKET)wsock); +#else + ::close(psock); +#endif + needs_closing = false; + } +} + + diff --git a/src/socket_common.hpp b/src/socket_common.hpp new file mode 100644 index 0000000..21acc9a --- /dev/null +++ b/src/socket_common.hpp @@ -0,0 +1,36 @@ +#ifndef UUID_6091A81C00E14F7F855C382F4C918DA5 +#define UUID_6091A81C00E14F7F855C382F4C918DA5 + +struct socket_common +{ + socket_common(); + socket_common(socket_common const& other); + ~socket_common(); + socket_common& operator=(socket_common const& other); + +protected: + struct socket_data + { + socket_data(); + ~socket_data(); + socket_data(socket_data const& other); + socket_data& operator=(socket_data const& other); + void set_needs_closing(); + void close(); + union + { + void* wsock; // winsock socket + int psock; // BSD POSIX socket + }; + int count; + private: + bool needs_closing; +#if BLAHNET_WIN32==1 + static int wsock_total_count; +#endif + }; + socket_data* data; +}; + +#endif // UUID_6091A81C00E14F7F855C382F4C918DA5 + diff --git a/src/socket_handle.cpp b/src/socket_handle.cpp deleted file mode 100644 index a0cd12c..0000000 --- a/src/socket_handle.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "socket_handle.hpp" - -socket_handle::socket_handle() -: data(new socket_handle_data()) -{ -} - -socket_handle::socket_handle(const socket_handle& other) -: data(other.data) -{ - ++data->count; -} - -socket_handle::~socket_handle() -{ - --data->count; - if (data->count == 0) - { - delete data; - } -} - -socket_handle& socket_handle::operator=(const socket_handle& other) -{ - socket_handle_data* const old = data; - data = other.data; - ++data->count; - if (--old->count == 0) - delete old; - return *this; - -} - -socket_handle::socket_handle_data::socket_handle_data() -: count(1) -{ - -} - - diff --git a/src/socket_handle.hpp b/src/socket_handle.hpp deleted file mode 100644 index 39cbb6f..0000000 --- a/src/socket_handle.hpp +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef UUID_6091A81C00E14F7F855C382F4C918DA5 -#define UUID_6091A81C00E14F7F855C382F4C918DA5 - -#include "address.hpp" - -struct socket_handle -{ - socket_handle(); - socket_handle(const socket_handle& other); - ~socket_handle(); - socket_handle& operator=(const socket_handle& other); - -private: - struct socket_handle_data - { - socket_handle_data(); - socket_handle_data(const socket_handle_data& other); - socket_handle_data& operator=(const socket_handle_data& other); - union - { - void* wsock; // winsock socket - int psock; // BSD POSIX socket - }; - int count; - }; - socket_handle_data* data; -}; - -void udp_socket(const socket_handle& handle); -void bind_socket(const socket_handle& handle, const address& address); - -#endif // UUID_6091A81C00E14F7F855C382F4C918DA5 - diff --git a/src/udp_socket.cpp b/src/udp_socket.cpp new file mode 100644 index 0000000..6a7b65a --- /dev/null +++ b/src/udp_socket.cpp @@ -0,0 +1,51 @@ +#include "udp_socket.hpp" +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <unistd.h> + +udp_socket::udp_socket() +{ +} + +int udp_socket::create() +{ + data->psock = ::socket(PF_INET, SOCK_DGRAM, 0); + if (data->psock == -1) + return -1; + data->set_needs_closing(); + return 0; +} + +/* TODO: real error handling */ + +int udp_socket::bind(unsigned short int port) +{ + address addr(port); + return ::bind(data->psock, + reinterpret_cast<sockaddr*>(addr.data()), + sizeof(sockaddr)); +} + +int udp_socket::sendto(void const* msg, std::size_t len, + address const& addr) +{ + return ::sendto(data->psock, msg, len, 0, + reinterpret_cast<sockaddr const*>(addr.data()), + sizeof(sockaddr)); +} + +int udp_socket::recvfrom(void* msg, std::size_t len, address& addr) +{ + socklen_t from_len = sizeof(sockaddr); + return ::recvfrom(data->psock, msg, len, 0, + reinterpret_cast<sockaddr*>(addr.data()), + &from_len); +} + +void udp_socket::close() +{ + data->close(); +} + diff --git a/src/udp_socket.hpp b/src/udp_socket.hpp new file mode 100644 index 0000000..b42489a --- /dev/null +++ b/src/udp_socket.hpp @@ -0,0 +1,19 @@ +#ifndef UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 +#define UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 + +#include "socket_common.hpp" +#include "address.hpp" +#include <cstring> + +struct udp_socket : public socket_common +{ + udp_socket(); + int create(); + int bind(unsigned short int port); + int sendto(void const* msg, std::size_t len, address const& addr); + int recvfrom(void* msg, std::size_t len, address& addr); + void close(); +}; + +#endif // UUID_96F8FCADA2CD4A1EAC27C1575447E3A7 +
darka/blahnet
dc12346a47881d96626a8d04c78f752ab2c1a245
bool rw
diff --git a/src/bit_stream.cpp b/src/bit_stream.cpp index 2026c7c..c06ad2f 100644 --- a/src/bit_stream.cpp +++ b/src/bit_stream.cpp @@ -1,200 +1,234 @@ #include "bit_stream.hpp" #include <iostream> #include <cstring> #include <cassert> bit_stream::bit_stream(std::size_t size_) : size_(size_) , cur_byte(0) , cur_rel_bit(0) { buffer = new buffer_type[size_]; memset(buffer, 0, size_); } bit_stream::bit_stream(const bit_stream& other) : size_(other.size_) , cur_byte(other.cur_byte) , cur_rel_bit(other.cur_rel_bit) { buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); } bit_stream::bit_stream(buffer_type* data, std::size_t size_) : buffer(data) , size_(size_) , cur_byte(0) , cur_rel_bit(0) { } bit_stream::~bit_stream() { clear(); } bit_stream& bit_stream::operator=(const bit_stream& other) { clear(); size_ = other.size_; cur_byte = other.cur_byte; cur_rel_bit = other.cur_rel_bit; buffer = new buffer_type[size_]; memcpy(buffer, other.buffer, size_); return *this; } void bit_stream::seek(unsigned int bit) { cur_byte = bit / 8; cur_rel_bit = bit % 8; } void bit_stream::affirm_size(std::size_t bits) { std::size_t new_size = size_; while (bits > (new_size - cur_byte) * 8 - cur_rel_bit) { new_size = new_size * 2; } if (new_size > size_) { std::cout << new_size << "\n"; resize(new_size); } } void bit_stream::resize(std::size_t new_size) { buffer_type* new_buffer = new buffer_type[new_size]; // TODO: some redundancy here memset(new_buffer, 0, new_size); memcpy(new_buffer, buffer, size_); delete[] buffer; buffer = new_buffer; size_ = new_size; } +void bit_stream::write_bool(bool n) +{ + write_bit(n); +} + void bit_stream::write_uint(uint32 n, unsigned int bits) { // TODO: throw if bits > 32 assert(bits <= 32); affirm_size(bits); unsigned int i = 0; // How many bits we've already written while (i < bits) { unsigned int bits_to_write; // How many bits we'll be writing // There are 2 possibilities, either we're writing until the end of the byte on the buffer // or we aren't! We have to make the choice from either if ((8 - cur_rel_bit) <= (bits - i)) { // We get here if we're writing to the end of the current byte // on the buffer bits_to_write = 8 - cur_rel_bit; buffer[cur_byte] |= (n >> (bits - i - bits_to_write)); ++cur_byte; } else { // We get here if writing all the bits we're still left to write // won't make us reach the end of the byte we're writing to bits_to_write = bits - i; uint8 portion = ((n << (8 - bits_to_write)) & 0xFF); portion >>= cur_rel_bit; buffer[cur_byte] |= portion; } i += bits_to_write; cur_rel_bit = (cur_rel_bit + bits_to_write) % 8; } } +bool bit_stream::read_bool() +{ + return read_bit(); +} + void bit_stream::write_sint(sint32 n, unsigned int bits) { write_uint(static_cast<uint32>(n), bits); } uint32 bit_stream::read_uint(unsigned int bits) { assert(bits <= 32); uint32 ret = 0; unsigned int i = 0; while (i < bits) { unsigned int bits_to_write; if ((bits - i) <= (8 - cur_rel_bit)) { // We're here because on the current byte in the buffer we have // bits to the right that we're supposed to skip bits_to_write = bits - i; uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; assert(bits_to_write <= 8); ret |= (portion >> (8 - bits_to_write)); } else { // We're here to read the current byte on the buffer from // cur_rel_bit till the end bits_to_write = 8 - cur_rel_bit; // Clear up the leftmost bits uint8 portion = (buffer[cur_byte] << cur_rel_bit) & 0xFF; portion >>= cur_rel_bit; assert(bits - i - bits_to_write <= bits); ret |= (portion << (bits - i - bits_to_write)); } i += bits_to_write; cur_rel_bit = cur_rel_bit + bits_to_write; if (cur_rel_bit >= 8) { ++cur_byte; cur_rel_bit %= 8; } } return ret; } sint32 bit_stream::read_sint(unsigned int bits) { return static_cast<sint32>(read_uint(bits)); } void bit_stream::write_string(const std::string& str) { write_uint(str.size(), 32); for (std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) { write_uint(*iter, 8); } } std::string bit_stream::read_string() { std::string ret; std::string::size_type chars = read_uint(32); for (std::string::size_type i = 0; i < chars; ++i) { ret.append(1, read_uint(8)); } return ret; } #if 0 void bit_stream::printContents() const { for (std::size_t i = 0; i < size_; ++i) { std::cout << static_cast<unsigned int>(buffer[i]) << "\n"; } } #endif void bit_stream::clear() { if (buffer != 0) delete[] buffer; } +void bit_stream::write_bit(bool bit) +{ + affirm_size(1); + buffer[cur_byte] |= (bit << (8 - cur_rel_bit - 1)); + inc_bit(); +} + +bool bit_stream::read_bit() +{ + bool ret = (buffer[cur_byte] >> (8 - cur_rel_bit - 1)) & 0x01; + inc_bit(); + return ret; +} + +void bit_stream::inc_bit() +{ + cur_rel_bit += 1; + if (cur_rel_bit == 8) + { + cur_byte += 1; + cur_rel_bit = 0; + } +} + diff --git a/src/bit_stream.hpp b/src/bit_stream.hpp index faacbf1..c718372 100644 --- a/src/bit_stream.hpp +++ b/src/bit_stream.hpp @@ -1,52 +1,59 @@ #ifndef UUID_3A39D07169584AA1A5A6E890BF40AEC4 #define UUID_3A39D07169584AA1A5A6E890BF40AEC4 #include "types.hpp" #include <cstddef> #include <string> #include <stdexcept> struct bit_stream { typedef uint8 buffer_type; // TODO: implement copy constructor and operator= bit_stream(std::size_t size=4); bit_stream(const bit_stream& other); bit_stream(buffer_type* data, std::size_t size); ~bit_stream(); bit_stream& operator=(const bit_stream& other); + void write_bool(bool n); + bool read_bool(); + void write_uint(uint32 n, unsigned int bits=32); uint32 read_uint(unsigned int bits); void write_sint(sint32 n, unsigned int bits=32); sint32 read_sint(unsigned int bits); void write_string(const std::string& str); std::string read_string(); const buffer_type* raw_data() const { return buffer; } buffer_type* raw_data() { return buffer; } std::size_t size() const { return size_; } #if 0 void printContents() const; #endif void seek(unsigned int bit); private: + void write_bit(bool bit); + bool read_bit(); + void inc_bit(); // increments cur_rel_bit and cur_byte if needed + void affirm_size(std::size_t bits); void resize(std::size_t new_size); void clear(); buffer_type* buffer; std::size_t size_; std::size_t cur_byte; // current byte unsigned int cur_rel_bit; // relative to current byte }; #endif // UUID_3A39D07169584AA1A5A6E890BF40AEC4
bret/pageadapter
ac3a73d3a812d0c8d622876d597e4c5d81f74146
initial todo list
diff --git a/todo.txt b/todo.txt new file mode 100644 index 0000000..5066a51 --- /dev/null +++ b/todo.txt @@ -0,0 +1,11 @@ +Features +* element can be defined +* element creates an instance method +* "helper" class methods +* can have additional instance methods +* pages can be included in other pages + +Change for Watir +* create match operator for watir + +how do we separate navigation from input/validation? \ No newline at end of file
bret/pageadapter
2a9bb46826961f264205ac0e2f9e641b2c0edad8
eclipse files
diff --git a/.loadpath b/.loadpath new file mode 100644 index 0000000..9a62220 --- /dev/null +++ b/.loadpath @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="UTF-8"?> +<loadpath> + <pathentry path="" type="src"/> + <pathentry path="org.rubypeople.rdt.launching.RUBY_CONTAINER" type="con"/> +</loadpath> diff --git a/.project b/.project new file mode 100644 index 0000000..366da16 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>pageadapter</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.rubypeople.rdt.core.rubybuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.rubypeople.rdt.core.rubynature</nature> + </natures> +</projectDescription>
sattellite/perl
094a1610627646f9e5b6cfed24cbbb3b391e76a3
ДОбавил в README про downloadAnounce.pl
diff --git a/README b/README index 07138a2..55a4586 100644 --- a/README +++ b/README @@ -1,9 +1,10 @@ ===== PERL scripts ===== = parser - create HTML page from RSSfeed (http://naklon.info/rss/about.htm) = tv_anounce - anounce.pl - create anouncements for 19 russian TV chanels - tv-programme - create a TV-programm for the 38 russian channels + - downloadAnounce.pl - downloading anounces from http://s-tv.ru = weather - rp5.pl - weather from rp5.ru for Bryansk - weather.pl - weather from google
sattellite/perl
fa8b5a84053cf23bd5a383fa4665ea1abcb78771
Теперь скачивает по эфирным неделям. И подогнал код под Perl::Critic
diff --git a/tv_anounce/downloadAnounce.pl b/tv_anounce/downloadAnounce.pl index cbc456e..ba2cfeb 100755 --- a/tv_anounce/downloadAnounce.pl +++ b/tv_anounce/downloadAnounce.pl @@ -1,94 +1,94 @@ #!/usr/bin/env perl use warnings; use strict; use LWP; use URI; use HTTP::Cookies; use File::Path qw(make_path); use IO::File; my $file = IO::File -> new; my $srvHost = "xmltv.s-tv.ru"; -my $login = "tv4853"; -my $pass = "JfWcXQpgGO"; +my $login = "test"; +my $pass = "test"; my $show = "1"; my $xmlTV = "1"; my $url = URI->new( "http://$srvHost/xchenel.php" ); $url->query_form( 'login' => $login, 'pass' => $pass, 'show' => $show, 'xmltv' => $xmlTV ); my $browser = LWP::UserAgent->new(); my $cookies = HTTP::Cookies->new(); $browser -> cookie_jar( $cookies ); $browser -> agent("Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8"); my $page = $browser -> get( $url ) -> content; while ( $page =~ /(\/xmltv.php\?prg=\d+\&sh\=0)\".+?>(.+?)<\/a>.+?(\d{4}\-\d{2}\-\d{2})/sgx ) { writeToFile( $2, $browser->post( "http://$srvHost$1" )->content, $3 ); } sub writeToFile { my ( $tvName, $content, $dir) = @_; make_path $dir unless -d $dir; $file -> open( "> $dir/$tvName\.xml"); print $file $content; $file -> close; print "Created file: \"$dir\/$tvName.xml\"\n"; return 1; } #writeToFile =head1 NAME Загрузчик телепрограммы с сайта L<< http://s-tv.ru >> в формате XMLTV. =head1 USAGE $ perl downloadAnounce.pl =head1 DESCRIPTION Скачивание файлов с телепрограммой с сайта L<< http://s-tv.ru >>. Скачанные файлы размещаются в директории, название которых соответствует началу эфирной недели. =head1 CONFIGURATION Для использования необходимо только поправить свои логин и пароль, которые хранятся в переменных $login и $pass. =head1 AUTHOR Aleksander Groschev E-Mail: L<< E<lt>[email protected]<gt> >> JabberID: L<< E<lt>[email protected]<gt> >> =head1 LICENSE AND COPYRIGHT Эта программа распространяется под лицензией MIT (MIT License) Copyright (c) 2010 Aleksander Groschev Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"), использовать Программное Обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, добавление, публикацию, распространение, сублицензирование и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется данное Программное Обеспечение, при соблюдении следующих условий: Вышеупомянутый копирайт и данные условия должны быть включены во все копии или значимые части данного Программного Обеспечения. ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ. =cut
sattellite/perl
826edc55ee3ea1d19f891c57a363a5f57337a25f
Теперь скачивает по эфирным неделям. И подогнал код под Perl::Critic
diff --git a/tv_anounce/downloadAnounce.pl b/tv_anounce/downloadAnounce.pl old mode 100644 new mode 100755 index 1223b34..cbc456e --- a/tv_anounce/downloadAnounce.pl +++ b/tv_anounce/downloadAnounce.pl @@ -1,105 +1,94 @@ #!/usr/bin/env perl -no warnings; +use warnings; use strict; use LWP; use URI; use HTTP::Cookies; use File::Path qw(make_path); +use IO::File; -my $directory = &date() ."_prog"; -make_path $directory unless -d $directory; +my $file = IO::File -> new; my $srvHost = "xmltv.s-tv.ru"; -my $login = "test"; -my $pass = "test"; +my $login = "tv4853"; +my $pass = "JfWcXQpgGO"; my $show = "1"; my $xmlTV = "1"; my $url = URI->new( "http://$srvHost/xchenel.php" ); $url->query_form( 'login' => $login, 'pass' => $pass, 'show' => $show, 'xmltv' => $xmlTV ); my $browser = LWP::UserAgent->new(); my $cookies = HTTP::Cookies->new(); $browser -> cookie_jar( $cookies ); $browser -> agent("Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8"); my $page = $browser -> get( $url ) -> content; -while ( $page =~ /(\/xmltv.php\?prg=\d+\&sh\=0)\".+?>(.+?)<\/a>/sg ) { - writeToFile( $2, $browser->post( "http://$srvHost$1" )->content ); +while ( $page =~ /(\/xmltv.php\?prg=\d+\&sh\=0)\".+?>(.+?)<\/a>.+?(\d{4}\-\d{2}\-\d{2})/sgx ) { + writeToFile( $2, $browser->post( "http://$srvHost$1" )->content, $3 ); } sub writeToFile { - if ( -e "$directory/$_[0].xml" ) { - make_path "$directory/next_week" unless -d "$directory/next_week"; - open ( FILE, ">", "$directory/next_week/$_[0].xml" ); - print FILE $_[0]; - close FILE; - print "Created file: \"next_week\/$_[0].xml\"\n"; - } else { - open ( FILE, ">", "$directory/$_[0].xml" ); - print FILE $_[1]; - close FILE; - print "Created file: \"$_[0].xml\"\n"; - } -} + my ( $tvName, $content, $dir) = @_; + make_path $dir unless -d $dir; + $file -> open( "> $dir/$tvName\.xml"); + print $file $content; + $file -> close; + print "Created file: \"$dir\/$tvName.xml\"\n"; + return 1; +} #writeToFile + +=head1 NAME -sub date -{ # Сегодняшняя дата - my ($d,$m,$y) = (localtime(time))[3,4,5]; - $y += 1900; $m += 1; +Загрузчик телепрограммы с сайта L<< http://s-tv.ru >> в формате XMLTV. - # Если число однозначное, то пририсовать ноль к нему - if(scalar split( '', $d ) == 1) { $d = '0'.$d }; - if(scalar split( '', $m ) == 1) { $m = '0'.$m }; +=head1 USAGE - my $dat = $y.'-'.$m.'-'.$d; - return $dat; -} # date + $ perl downloadAnounce.pl -=head1 ОПИСАНИЕ +=head1 DESCRIPTION -Скачивание файлов с телепрограммой с сайта L<< http://s-tv.ru >> +Скачивание файлов с телепрограммой с сайта L<< http://s-tv.ru >>. +Скачанные файлы размещаются в директории, название которых соответствует +началу эфирной недели. -=head1 ИСПОЛЬЗОВАНИЕ +=head1 CONFIGURATION - ./downloadAnounce.pl - И выбор номера необходимого канала. +Для использования необходимо только поправить свои логин и пароль, которые +хранятся в переменных $login и $pass. -=head1 АВТОР +=head1 AUTHOR Aleksander Groschev E-Mail: L<< E<lt>[email protected]<gt> >> JabberID: L<< E<lt>[email protected]<gt> >> -=head1 ЛИЦЕНЗИЯ +=head1 LICENSE AND COPYRIGHT Эта программа распространяется под лицензией MIT (MIT License) Copyright (c) 2010 Aleksander Groschev Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"), использовать Программное Обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, добавление, публикацию, распространение, сублицензирование и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется данное Программное Обеспечение, при соблюдении следующих условий: Вышеупомянутый копирайт и данные условия должны быть включены во все копии или значимые части данного Программного Обеспечения. ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ. -=head4 TODO -1. Сделать проверку в 23 и 31 строках. - =cut
sattellite/perl
f525de350a57cf526c22bdff9bfcc9b0d651bf31
Обновил немного код. Теперь на две недели разделяет файлы, если они там присутствуют.
diff --git a/tv_anounce/downloadAnounce.pl b/tv_anounce/downloadAnounce.pl old mode 100755 new mode 100644 index 39933f4..2f36086 --- a/tv_anounce/downloadAnounce.pl +++ b/tv_anounce/downloadAnounce.pl @@ -1,80 +1,105 @@ #!/usr/bin/env perl -use warnings; +no warnings; use strict; use LWP; use URI; use HTTP::Cookies; +use File::Path qw(make_path); + +my $directory = &date() ."_prog"; +make_path $directory unless -d $directory; my $srvHost = "xmltv.s-tv.ru"; -my $login = "test"; +my $login = "test; my $pass = "test"; my $show = "1"; my $xmlTV = "1"; my $url = URI->new( "http://$srvHost/xchenel.php" ); $url->query_form( 'login' => $login, 'pass' => $pass, 'show' => $show, 'xmltv' => $xmlTV ); my $browser = LWP::UserAgent->new(); my $cookies = HTTP::Cookies->new(); $browser -> cookie_jar( $cookies ); $browser -> agent("Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8"); my $page = $browser -> get( $url ) -> content; while ( $page =~ /(\/xmltv.php\?prg=\d+\&sh\=0)\".+?>(.+?)<\/a>/sg ) { writeToFile( $2, $browser->post( "http://$srvHost$1" )->content ); } sub writeToFile { - open (FILE, ">", "prog/$_[0].xml" ); - print FILE $_[1]; - close FILE; - print "Created file: \"$_[0].xml\"\n"; + if ( -e "$directory/$_[0].xml" ) { + make_path "$directory/next_week" unless -d "$directory/next_week"; + open ( FILE, ">", "$directory/next_week/$_[0].xml" ); + print FILE $_[0]; + close FILE; + print "Created file: \"next_week\/$_[0].xml\"\n"; + } else { + open ( FILE, ">", "$directory/$_[0].xml" ); + print FILE $_[1]; + close FILE; + print "Created file: \"$_[0].xml\"\n"; + } } +sub date +{ # Сегодняшняя дата + my ($d,$m,$y) = (localtime(time))[3,4,5]; + $y += 1900; $m += 1; + + # Если число однозначное, то пририсовать ноль к нему + if(scalar split( '', $d ) == 1) { $d = '0'.$d }; + if(scalar split( '', $m ) == 1) { $m = '0'.$m }; + + my $dat = $y.'-'.$m.'-'.$d; + return $dat; +} # date + =head1 ОПИСАНИЕ Скачивание файлов с телепрограммой с сайта L<< http://s-tv.ru >> =head1 ИСПОЛЬЗОВАНИЕ ./downloadAnounce.pl И выбор номера необходимого канала. =head1 АВТОР Aleksander Groschev E-Mail: L<< E<lt>[email protected]<gt> >> JabberID: L<< E<lt>[email protected]<gt> >> =head1 ЛИЦЕНЗИЯ Эта программа распространяется под лицензией MIT (MIT License) Copyright (c) 2010 Aleksander Groschev Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"), использовать Программное Обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, добавление, публикацию, распространение, сублицензирование и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется данное Программное Обеспечение, при соблюдении следующих условий: Вышеупомянутый копирайт и данные условия должны быть включены во все копии или значимые части данного Программного Обеспечения. ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ. =head4 TODO 1. Сделать проверку в 23 и 31 строках. =cut
sattellite/perl
0ae5a946a13036d3c4e95dd97a7dfef960de98c5
Скачивание фалов с теле программой
diff --git a/tv_anounce/downloadAnounce.pl b/tv_anounce/downloadAnounce.pl new file mode 100755 index 0000000..39933f4 --- /dev/null +++ b/tv_anounce/downloadAnounce.pl @@ -0,0 +1,80 @@ +#!/usr/bin/env perl +use warnings; +use strict; + +use LWP; +use URI; +use HTTP::Cookies; + +my $srvHost = "xmltv.s-tv.ru"; +my $login = "test"; +my $pass = "test"; +my $show = "1"; +my $xmlTV = "1"; + +my $url = URI->new( "http://$srvHost/xchenel.php" ); +$url->query_form( 'login' => $login, 'pass' => $pass, 'show' => $show, 'xmltv' => $xmlTV ); + +my $browser = LWP::UserAgent->new(); +my $cookies = HTTP::Cookies->new(); +$browser -> cookie_jar( $cookies ); +$browser -> agent("Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8"); + +my $page = $browser -> get( $url ) -> content; + +while ( $page =~ /(\/xmltv.php\?prg=\d+\&sh\=0)\".+?>(.+?)<\/a>/sg ) { + writeToFile( $2, $browser->post( "http://$srvHost$1" )->content ); +} + +sub writeToFile +{ + open (FILE, ">", "prog/$_[0].xml" ); + print FILE $_[1]; + close FILE; + print "Created file: \"$_[0].xml\"\n"; +} + +=head1 ОПИСАНИЕ + +Скачивание файлов с телепрограммой с сайта L<< http://s-tv.ru >> + +=head1 ИСПОЛЬЗОВАНИЕ + + ./downloadAnounce.pl + И выбор номера необходимого канала. + +=head1 АВТОР + +Aleksander Groschev +E-Mail: L<< E<lt>[email protected]<gt> >> +JabberID: L<< E<lt>[email protected]<gt> >> + +=head1 ЛИЦЕНЗИЯ + +Эта программа распространяется под лицензией MIT (MIT License) + +Copyright (c) 2010 Aleksander Groschev + +Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного +обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное +Обеспечение"), использовать Программное Обеспечение без ограничений, включая +неограниченное право на использование, копирование, изменение, добавление, публикацию, +распространение, сублицензирование и/или продажу копий Программного Обеспечения, +также как и лицам, которым предоставляется данное Программное Обеспечение, при +соблюдении следующих условий: + +Вышеупомянутый копирайт и данные условия должны быть включены во все копии или +значимые части данного Программного Обеспечения. + +ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ, +ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ +ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ +СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ +УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, +ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ +ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ. + +=head4 TODO +1. Сделать проверку в 23 и 31 строках. + +=cut
sattellite/perl
90c46e3c14a8deeefe1c236bfe71a8892cb06fb4
Ugly ugly ugly
diff --git a/tv_anounce/tv-programme.pl b/tv_anounce/tv-programme.pl index 094da59..9566a5d 100644 --- a/tv_anounce/tv-programme.pl +++ b/tv_anounce/tv-programme.pl @@ -1,86 +1,111 @@ #!/usr/bin/env perl use strict; use warnings; no warnings "all"; - +use utf8; use XML::Simple; +use IO::Uncompress::Gunzip qw(gunzip $GunzipError); use IO::File; use File::Path qw(make_path); -use utf8; +use File::Download; my %month = ( '01' => 'января', '02' => 'февраля', '03' => 'марта', '04' => 'апреля', '05' => 'мая', '06' => 'июня', '07' => 'июля', '08' => 'августа', '09' => 'сентября', '10' => 'октября', '11' => 'ноября', '12' => 'декабря' ); my %day = ( '1' => 'Понедельник. ', '2' => 'Вторник. ', '3' => 'Среда. ', '4' => 'Четверг. ', '5' => 'Пятница. ', '6' => 'Суббота. ', '7' => 'Воскресенье. ', '8' => 'Понедельник. ' ); +{ # Скачивание и распаковка файла с ТВ-программой + my $url = 'http://www.teleguide.info/download/new3/xmltv.xml.gz'; + my $dwn = File::Download->new({ + overwrite => 1, + }); + + if ($dwn->download($url) == 0) { + print "Скачиваю программу на неделю.\n"; + $dwn->download( $url ); + } else { + die "Не могу загрузить файл по ссылке $url"; + } + + my $fileIn = "xmltv.xml.gz"; + my $fileOut = "xmltv.xml"; + print "Распаковываю скачанный файл.\n"; + gunzip $fileIn => $fileOut or die "$GunzipError"; +} + +print "Подготовка к обработке.\n"; my $fileHandle = IO::File->new( 'xmltv.xml' ); my $xmlTree = XMLin( $fileHandle ); +print "Обработка и создание файлов\n\n"; + my $directory = &date(); make_path $directory unless -d $directory; my @channelID = qw(1 2 676 4 104 101 103 109 209 235 100052 663 226 326 288 300047 289 3 105 300020 595 272 300007 100010 5 107 108 503 300003 727 300035 255 325 222 313 330 100018 100017); my $progData = $xmlTree->{'programme'}; foreach my $channel ( @channelID ) { my $dayCounter = "1"; my ( $times, $d, $title, $out ); my $createFile = "$xmlTree->{'channel'}->{$channel}->{'display-name'}->{'content'}"; for ( my $i = 0; $i < @$progData; $i++ ) { my $progNow = @$progData->["$i"]; if ( ( $progNow->{'channel'} ) == $channel ) { my $date = $progNow->{'start'}; if ( $progNow->{'desc'}->{'content'} ) { $title = $progNow->{'title'}->{'content'}."\n<br><em>".$progNow->{'desc'}->{'content'}.'</em><br>'; } else { $title = $progNow->{'title'}->{'content'}.'<br>'; } $date =~ m/(....)(..)(..)(..)(..).+?/si; if ( $d ne $3 ) { $times = '<br><h3><strong>'.$day{"$dayCounter"}.$3.' '.$month{"$2"}."<\/strong><\/h3><hr><br>\n<strong><span style=\"color: #3366ff\">".$4.':'.$5.'</span></strong>'; $d = $3; $dayCounter++; } else { $times = '<strong><span style="color: #3366ff">'.$4.':'.$5.'</span></strong>'; } $out .= "$times $title\n"; } } $out =~ s/^<br><h3>/<h3>/i; &writeToFile( $createFile, $out ); } +print "\nЗавершение работы скрипта.\n"; + sub date { # Сегодняшняя дата my ($d,$m,$y) = (localtime(time))[3,4,5]; $y += 1900; $m += 1; # Если число однозначное, то пририсовать ноль к нему if(scalar split( '', $d ) == 1) { $d = '0'.$d }; if(scalar split( '', $m ) == 1) { $m = '0'.$m }; my $dat = $y.'-'.$m.'-'.$d; return $dat; } # date sub writeToFile { # Запись в файл open (FILE, ">", "$directory/$_[0]" ); print FILE $_[1]; close FILE; print "Создан файл: \"$_[0]\"\n"; } # writeToFile