repo
string
commit
string
message
string
diff
string
lethain/mahou
bf927144a468e3b2ced44d6f3df4a52466512a96
Can now restrict queries by Delicious popular feed.
diff --git a/main.py b/main.py index b6822c8..d7ed4b3 100755 --- a/main.py +++ b/main.py @@ -1,76 +1,88 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. __author__ = "Vik Singh ([email protected])" import logging import wsgiref.handlers from google.appengine.ext import webapp from yos.crawl.rest import download -from yos.util import console +from yos.util import text, console from yos.boss import ysearch -from yos.yql import db +from yos.yql import udfs, db from django.utils import simplejson class ImageSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) data = ysearch.search(query,vertical="images",count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) class NewsSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) data = ysearch.search(query,vertical="news",count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) + +def overlap_predicate(r1,r2): + return text.overlap(r1['title'],r2['title']) > 1 + class WebSearchHandler(webapp.RequestHandler): + + def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) - data = ysearch.search(query,count=20,start=offset); - images = db.create(data=data) - serialized = simplejson.dumps(images.rows) + includeDelicious = console.strfix(self.request.get("includeDelicious")) + + search_results = ysearch.search(query,count=20,start=offset); + web = db.create(data=search_results) + if len(includeDelicious) == 4: + dl = db.select(udfs.unnest_value, name="dl", url=u"http://feeds.delicious.com/rss/popular/%s" % query) + web = db.join(overlap_predicate,[web,dl]) + + serialized = simplejson.dumps(web.rows) self.response.out.write(serialized) class RootHandler(webapp.RequestHandler): def get(self): self.redirect(ROOT_REDIRECT) def main(): logging.getLogger().setLevel(logging.DEBUG) application = webapp.WSGIApplication([('/', RootHandler), ('/search/images', ImageSearchHandler), ('/search/web', WebSearchHandler), ('/search/news', NewsSearchHandler), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() diff --git a/yos/yql/udfs.py b/yos/yql/udfs.py index fd6e937..1194476 100644 --- a/yos/yql/udfs.py +++ b/yos/yql/udfs.py @@ -1,24 +1,24 @@ # Copyright (c) 2008 Yahoo! Inc. All rights reserved. # Licensed under the Yahoo! Search BOSS Terms of Use # (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html) """ Some handy user defined functions to plug in db.select """ __author__ = "Vik Singh ([email protected])" -from util.typechecks import is_dict +from yos.util.typechecks import is_dict def unnest_value(row): """ For data collections which have nested value parameters (like RSS) this function will unnest the value to the higher level. For example, say the row is {"title":{"value":"yahoo wins search"}} This function will take that row and return the following row {"title": "yahoo wins search"} """ nr = {} for k, v in row.iteritems(): if is_dict(type(v)) and "value" in v: nr[k] = v["value"] else: nr[k] = v return nr
lethain/mahou
5798331d8ad9e3917610ca5675e7ca13bff14d30
Minor UI response when clicking on a web result.
diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index 1ebbfbe..31e93e8 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,108 +1,117 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" import "WLHTMLTextField.j" @implementation WLWebResultsView : WLResultsView { BOOL _includeDelcious; } -(id)initWithFrame: (CPRect)aFrame { self = [super initWithFrame:aFrame]; _includeDelicious = NO; return self; } -(void)setIncludeDelicious: (BOOL)aBool { _includeDelicious = aBool; } -(BOOL)includeDelicious { return _includeDelicious; } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(325,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset+"&includeDelicious="+[self includeDelicious]; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; frame = CGRectMake(5,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; frame = CGRectMake(5,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setSelectable:YES]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setSelectable:YES]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } +-(void)setSelected:(BOOL)flag { + if (flag) { + [webView setBackgroundColor:[CPColor lightGrayColor]]; + } + else { + [webView setBackgroundColor:[CPColor whiteColor]]; + } +} + @end
lethain/mahou
9d6073618a20ff16d35c7535432f9c1bd6f1858d
Uncommented the extra data for pictures.
diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index fd0175d..3797f62 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,81 +1,82 @@ import <Foundation/CPObject.j> import "WLResultsView.j" +import "WLImageDisplayView.j" @implementation WLImageResultsView : WLResultsView { } -(CPSize)_minItemSize { return CGSizeMake(150,150); } -(CPSize)_maxItemSize { return CGSizeMake(150,150); } -(CPCollectionViewItem)_itemPrototype { return [[PhotoCell alloc] init]; } -(void)_search { var query = "/search/images?query="+encodeURIComponent(_searchString)+"&offset="+_offset; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } -/* -(void)setSelected:(BOOL)flag { if (!flag) return; //var view = [[imageView superview] superview]; //var bounds = [view bounds]; var mainWindow = [[CPApplication sharedApplication] mainWindow]; var point = [imageView convertRect:[imageView bounds] toView:[mainWindow contentView]]; var window = [[CPPanel alloc] initWithContentRect:CGRectMake(CGRectGetMinX(point),CGRectGetMinY(point),300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; var contentView = [window contentView]; var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(0,0,300,300) data:dict image:image]; [[window contentView] addSubview:aView]; [window orderFront:self]; -*/ } +@end +
lethain/mahou
5f68cc7c4b8f77765cb097df6e4d551d46f348a9
Not 100% perfect, but caches position and allows changing search.
diff --git a/static/WLResultsView.j b/static/WLResultsView.j index 896c2be..056c3a8 100644 --- a/static/WLResultsView.j +++ b/static/WLResultsView.j @@ -1,101 +1,102 @@ import <Foundation/CPObject.j> import "WLScrollView.j" @implementation WLResultsView : WLScrollView { CPArray _results; CPString _searchString; CPCollectionView _collectionView; int _offset; BOOL _recieved; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; [self createCollectionView]; [self setAutohidesScrollers:YES]; return self; } -(void)createCollectionView { var bounds = [self bounds]; var aFrame = CPRectMake(0,0, CGRectGetWidth(bounds)-20,CGRectGetHeight(bounds)); _collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [_collectionView setDelegate:self]; [_collectionView setItemPrototype:[self _itemPrototype]]; [_collectionView setMinItemSize:[self _minItemSize]]; [_collectionView setMaxItemSize:[self _maxItemSize]]; [_collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:_collectionView]; } -(CPSize)_minItemSize { return CGSizeMake(150,150); } -(CPSize)_maxItemSize { return CGSizeMake(150,150); } -(CPCollectionViewItem)_itemPrototype { // implement in subclass } -(void)searchFor: (CPString)searchString { if ([_searchString caseInsensitiveCompare:searchString]==0) { // Don't re-search already search results. return; } [self _clearResults]; _searchString = searchString; _offset = 0; [self _search]; _offset = _offset + [self _offsetIncrement]; } -(int)_offsetIncrement { return 20; } -(void)_clearResults { + [self createCollectionView]; _results = [[CPArray alloc] init]; } -(void)_setResults: (CPArray)anArray { [_results addObjectsFromArray:anArray]; [self _resultsUpdated]; _recieved = YES; } -(void)scrollerMovedToPosition: (float)scrollerPos { if (scrollerPos > 0.8 && _recieved != NO) { _recieved = NO; [self _search]; } } -(void)_resultsUpdated { [_collectionView setContent:[]]; //[self createCollectionView]; [_collectionView setContent:_results]; } -(void)_search { // perform search, update with _setResults method. } -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { [self _setResults:eval(data)]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { //alert("error: " + error); } -(void)connectionDidFinishLoading:(CPURLConnection)connection { // finished } @end
lethain/mahou
7f05988a24112721e1542aaa644a581f0824a578
Correctly caching position in results queue when new results come in.
diff --git a/static/WLResultsView.j b/static/WLResultsView.j index 611bb41..896c2be 100644 --- a/static/WLResultsView.j +++ b/static/WLResultsView.j @@ -1,92 +1,101 @@ import <Foundation/CPObject.j> import "WLScrollView.j" @implementation WLResultsView : WLScrollView { CPArray _results; CPString _searchString; CPCollectionView _collectionView; int _offset; BOOL _recieved; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; + [self createCollectionView]; + [self setAutohidesScrollers:YES]; + return self; +} + +-(void)createCollectionView { + var bounds = [self bounds]; + var aFrame = CPRectMake(0,0, + CGRectGetWidth(bounds)-20,CGRectGetHeight(bounds)); + _collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [_collectionView setDelegate:self]; [_collectionView setItemPrototype:[self _itemPrototype]]; [_collectionView setMinItemSize:[self _minItemSize]]; [_collectionView setMaxItemSize:[self _maxItemSize]]; [_collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:_collectionView]; - [self setAutohidesScrollers:YES]; - return self; } -(CPSize)_minItemSize { return CGSizeMake(150,150); } -(CPSize)_maxItemSize { return CGSizeMake(150,150); } -(CPCollectionViewItem)_itemPrototype { // implement in subclass } -(void)searchFor: (CPString)searchString { if ([_searchString caseInsensitiveCompare:searchString]==0) { // Don't re-search already search results. return; } [self _clearResults]; _searchString = searchString; _offset = 0; [self _search]; _offset = _offset + [self _offsetIncrement]; } -(int)_offsetIncrement { return 20; } -(void)_clearResults { _results = [[CPArray alloc] init]; } -(void)_setResults: (CPArray)anArray { [_results addObjectsFromArray:anArray]; [self _resultsUpdated]; _recieved = YES; } -(void)scrollerMovedToPosition: (float)scrollerPos { if (scrollerPos > 0.8 && _recieved != NO) { _recieved = NO; [self _search]; } } -(void)_resultsUpdated { [_collectionView setContent:[]]; + //[self createCollectionView]; [_collectionView setContent:_results]; } -(void)_search { // perform search, update with _setResults method. } -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { [self _setResults:eval(data)]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { //alert("error: " + error); } -(void)connectionDidFinishLoading:(CPURLConnection)connection { // finished } @end diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index 5527c25..1ebbfbe 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,108 +1,108 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" import "WLHTMLTextField.j" @implementation WLWebResultsView : WLResultsView { BOOL _includeDelcious; } -(id)initWithFrame: (CPRect)aFrame { self = [super initWithFrame:aFrame]; _includeDelicious = NO; return self; } -(void)setIncludeDelicious: (BOOL)aBool { _includeDelicious = aBool; } -(BOOL)includeDelicious { return _includeDelicious; } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(325,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset+"&includeDelicious="+[self includeDelicious]; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; frame = CGRectMake(5,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; - frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); + frame = CGRectMake(5,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setSelectable:YES]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setSelectable:YES]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } @end
lethain/mahou
a2b3b62c62c59bdbcc99945c5803483bf4499501
Can now toggle searching on Delicious (although, no backend uspport)
diff --git a/static/AppController.j b/static/AppController.j index a68d38d..7b44a2d 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,251 +1,267 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLResultsView.j" import "WLImageResultsView.j" import "WLWebResultsView.j" import "WLNewsResultsView.j" import "WLURLLabel.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; CPView webView; CPView imageView; CPView newsView; CPWindow aboutWindow; + CPMenuItem _toggleDelicious; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { CPLogRegister(CPLogConsole); var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; [self setupAboutWindow]; [theWindow orderFront:self]; [self setupMainMenu]; [CPMenu setMenuBarVisible:YES]; } -(void)search: (id)sender { var selectedItem = [tabView selectedTabViewItem]; var selectedView = [selectedItem view]; [selectedView searchFor:[searchField stringValue]]; } -(void)tabView:(CPTabView)aTabView didSelectTabViewItem: (CPTabViewItem)anItem { if ([[searchField stringValue] length] > 0) { [self search:self]; } } -(void)setupMainMenu { var m = [[CPMenu alloc] initWithTitle:@"MainMenu"]; [[CPApplication sharedApplication] setMainMenu:m]; // Web Menu var webMenuItem = [[CPMenuItem alloc] initWithTitle:@"Web" action:@selector(doNothing:) keyEquivalent:@"W"]; + var webMenu = [[CPMenu alloc] initWithTitle:@"Web"]; + _toggleDelicious = [[CPMenuItem alloc] initWithTitle:@"include Delicious" action:@selector(toggleDelicious:) keyEquivalent:@""]; + + [webMenu addItem:_toggleDelicious]; + [webMenuItem setSubmenu:webMenu]; + + [m addItem:webMenuItem]; + /* var imageMenuItem = [[CPMenuItem alloc] initWithTitle:@"Image" action:@selector(doNothing:) keyEquivalent:@"I"]; [m addItem:imageMenuItem]; var newsMenuItem = [[CPMenuItem alloc] initWithTitle:@"News" action:@selector(doNothing:) keyEquivalent:@"N"]; [m addItem:newsMenuItem]; - + */ [m addItem:[CPMenuItem separatorItem]]; var aboutMenuItem = [[CPMenuItem alloc] initWithTitle:@"About" action:@selector(toggleAboutWindow:) keyEquivalent:@"A"]; - [m addItem:aboutMenuItem]; - - } --(void)doNothing:(id)sender { - alert("blah"); +-(void)toggleDelicious:(id)sender { + if ([_toggleDelicious state] == CPOnState) { + [_toggleDelicious setState:CPOffState]; + [webView setIncludeDelicious:NO]; + } + else { + [_toggleDelicious setState:CPOnState]; + [webView setIncludeDelicious:YES]; + } } + +-(void)doNothing:(id)sender {} + -(void)toggleAboutWindow:(id)sender { if ([aboutWindow isVisible]==YES) { [aboutWindow orderOut:self]; } else { [aboutWindow orderFront:self]; } } -(void)setupAboutWindow { //var mainWindow = [[CPApplication sharedApplication] mainWindow]; //var bounds = [mainWindow bounds]; var frame = CGRectMake(150,150,300,200); var aboutWindow = [[CPWindow alloc] initWithContentRect:frame styleMask:CPClosableWindowMask|CPTitledWindowMask|CPHUDBackgroundWindowMask]; [aboutWindow setTitle:@"About Mahou"]; var contentView = [aboutWindow contentView]; var titleLabel = [self makeURLLabelWith:@"Will Larson (http://lethain.com/)" andUrl:@"http://lethain.com/" at:CPRectMake(0,0,300,30)]; [titleLabel setTextColor:[CPColor lightGrayColor]]; [titleLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [titleLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:titleLabel]; var uLabel = [self makeLabelWith:@"Made using" at:CPRectMake(0,30,300,30)]; [uLabel setTextColor:[CPColor whiteColor]]; [uLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [uLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:uLabel]; var cLabel = [self makeURLLabelWith:@"Cappuccino" andUrl:@"http://cappuccino.org/" at:CPRectMake(0,60,300,30)]; [cLabel setTextColor:[CPColor blueColor]]; [cLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [cLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:cLabel]; var yLabel = [self makeURLLabelWith:@"Yahoo! BOSS" andUrl:@"http://developer.yahoo.com/search/boss/" at:CPRectMake(0,90,300,30)]; [yLabel setTextColor:[CPColor blueColor]]; [yLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [yLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:yLabel]; var gLabel = [self makeURLLabelWith:@"Google App Engine" andUrl:@"http://code.google.com/appengine/" at:CPRectMake(0,120,300,30)]; [gLabel setTextColor:[CPColor blueColor]]; [gLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [gLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:gLabel]; } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; [tabView setTabViewType:CPTopTabsBezelBorder]; [contentView addSubview:tabView]; //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; webView = [[WLWebResultsView alloc] initWithFrame:frame]; imageView = [[WLImageResultsView alloc] initWithFrame:frame]; newsView = [[WLNewsResultsView alloc] initWithFrame:frame]; [webSearchTabItem setLabel:@"Web"]; [imageSearchTabItem setLabel:@"Image"]; [newsSearchTabItem setLabel:@"News"]; [webSearchTabItem setView:webView]; [imageSearchTabItem setView:imageView]; [newsSearchTabItem setView:newsView]; [tabView addTabViewItem:webSearchTabItem]; [tabView addTabViewItem:imageSearchTabItem]; [tabView addTabViewItem:newsSearchTabItem]; //[tabView selectTabViewItem:imageSearchTabItem]; [tabView setDelegate:self]; } @end diff --git a/static/Resources/CPApplication/New.png b/static/Resources/CPApplication/New.png new file mode 100644 index 0000000..16c1817 Binary files /dev/null and b/static/Resources/CPApplication/New.png differ diff --git a/static/Resources/CPApplication/NewHighlighted.png b/static/Resources/CPApplication/NewHighlighted.png new file mode 100644 index 0000000..4202382 Binary files /dev/null and b/static/Resources/CPApplication/NewHighlighted.png differ diff --git a/static/Resources/CPApplication/Open.png b/static/Resources/CPApplication/Open.png new file mode 100644 index 0000000..b902ce8 Binary files /dev/null and b/static/Resources/CPApplication/Open.png differ diff --git a/static/Resources/CPApplication/OpenHighlighted.png b/static/Resources/CPApplication/OpenHighlighted.png new file mode 100644 index 0000000..1982a6f Binary files /dev/null and b/static/Resources/CPApplication/OpenHighlighted.png differ diff --git a/static/Resources/CPApplication/Save.png b/static/Resources/CPApplication/Save.png new file mode 100644 index 0000000..8a1c6b7 Binary files /dev/null and b/static/Resources/CPApplication/Save.png differ diff --git a/static/Resources/CPApplication/SaveHighlighted.png b/static/Resources/CPApplication/SaveHighlighted.png new file mode 100644 index 0000000..e84e392 Binary files /dev/null and b/static/Resources/CPApplication/SaveHighlighted.png differ diff --git a/static/Resources/CPButton/CPButtonHUDRegular0.png b/static/Resources/CPButton/CPButtonHUDRegular0.png new file mode 100644 index 0000000..158e785 Binary files /dev/null and b/static/Resources/CPButton/CPButtonHUDRegular0.png differ diff --git a/static/Resources/CPButton/CPButtonHUDRegular1.png b/static/Resources/CPButton/CPButtonHUDRegular1.png new file mode 100644 index 0000000..31fb7a1 Binary files /dev/null and b/static/Resources/CPButton/CPButtonHUDRegular1.png differ diff --git a/static/Resources/CPButton/CPButtonHUDRegular2.png b/static/Resources/CPButton/CPButtonHUDRegular2.png new file mode 100644 index 0000000..2151e8e Binary files /dev/null and b/static/Resources/CPButton/CPButtonHUDRegular2.png differ diff --git a/static/Resources/CPButton/CPButtonHUDRegularHighlighted0.png b/static/Resources/CPButton/CPButtonHUDRegularHighlighted0.png new file mode 100644 index 0000000..78d5e3a Binary files /dev/null and b/static/Resources/CPButton/CPButtonHUDRegularHighlighted0.png differ diff --git a/static/Resources/CPButton/CPButtonHUDRegularHighlighted1.png b/static/Resources/CPButton/CPButtonHUDRegularHighlighted1.png new file mode 100644 index 0000000..62afef8 Binary files /dev/null and b/static/Resources/CPButton/CPButtonHUDRegularHighlighted1.png differ diff --git a/static/Resources/CPButton/CPButtonHUDRegularHighlighted2.png b/static/Resources/CPButton/CPButtonHUDRegularHighlighted2.png new file mode 100644 index 0000000..b4a9bd6 Binary files /dev/null and b/static/Resources/CPButton/CPButtonHUDRegularHighlighted2.png differ diff --git a/static/Resources/CPButton/CPButtonRoundRectRegular0.png b/static/Resources/CPButton/CPButtonRoundRectRegular0.png new file mode 100644 index 0000000..bd44dd4 Binary files /dev/null and b/static/Resources/CPButton/CPButtonRoundRectRegular0.png differ diff --git a/static/Resources/CPButton/CPButtonRoundRectRegular1.png b/static/Resources/CPButton/CPButtonRoundRectRegular1.png new file mode 100644 index 0000000..e874e8d Binary files /dev/null and b/static/Resources/CPButton/CPButtonRoundRectRegular1.png differ diff --git a/static/Resources/CPButton/CPButtonRoundRectRegular2.png b/static/Resources/CPButton/CPButtonRoundRectRegular2.png new file mode 100644 index 0000000..9519845 Binary files /dev/null and b/static/Resources/CPButton/CPButtonRoundRectRegular2.png differ diff --git a/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted0.png b/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted0.png new file mode 100644 index 0000000..0767982 Binary files /dev/null and b/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted0.png differ diff --git a/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted1.png b/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted1.png new file mode 100644 index 0000000..cea0792 Binary files /dev/null and b/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted1.png differ diff --git a/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted2.png b/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted2.png new file mode 100644 index 0000000..e1850b4 Binary files /dev/null and b/static/Resources/CPButton/CPButtonRoundRectRegularHighlighted2.png differ diff --git a/static/Resources/CPButton/CPButtonTexturedRoundedRegular0.png b/static/Resources/CPButton/CPButtonTexturedRoundedRegular0.png new file mode 100644 index 0000000..79fd351 Binary files /dev/null and b/static/Resources/CPButton/CPButtonTexturedRoundedRegular0.png differ diff --git a/static/Resources/CPButton/CPButtonTexturedRoundedRegular1.png b/static/Resources/CPButton/CPButtonTexturedRoundedRegular1.png new file mode 100644 index 0000000..7ab71cc Binary files /dev/null and b/static/Resources/CPButton/CPButtonTexturedRoundedRegular1.png differ diff --git a/static/Resources/CPButton/CPButtonTexturedRoundedRegular2.png b/static/Resources/CPButton/CPButtonTexturedRoundedRegular2.png new file mode 100644 index 0000000..49b44ab Binary files /dev/null and b/static/Resources/CPButton/CPButtonTexturedRoundedRegular2.png differ diff --git a/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted0.png b/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted0.png new file mode 100644 index 0000000..39768db Binary files /dev/null and b/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted0.png differ diff --git a/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted1.png b/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted1.png new file mode 100644 index 0000000..0b44ef2 Binary files /dev/null and b/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted1.png differ diff --git a/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted2.png b/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted2.png new file mode 100644 index 0000000..bc6a7bc Binary files /dev/null and b/static/Resources/CPButton/CPButtonTexturedRoundedRegularHighlighted2.png differ diff --git a/static/Resources/CPImageView/CPImageViewBottomLeftShadow.png b/static/Resources/CPImageView/CPImageViewBottomLeftShadow.png new file mode 100644 index 0000000..654ef3c Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewBottomLeftShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewBottomRightShadow.png b/static/Resources/CPImageView/CPImageViewBottomRightShadow.png new file mode 100644 index 0000000..93780f2 Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewBottomRightShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewBottomShadow.png b/static/Resources/CPImageView/CPImageViewBottomShadow.png new file mode 100644 index 0000000..5fc3ef0 Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewBottomShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewLeftShadow.png b/static/Resources/CPImageView/CPImageViewLeftShadow.png new file mode 100644 index 0000000..a67f66f Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewLeftShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewRightShadow.png b/static/Resources/CPImageView/CPImageViewRightShadow.png new file mode 100644 index 0000000..1b3cf77 Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewRightShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewTopLeftShadow.png b/static/Resources/CPImageView/CPImageViewTopLeftShadow.png new file mode 100644 index 0000000..2330564 Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewTopLeftShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewTopRightShadow.png b/static/Resources/CPImageView/CPImageViewTopRightShadow.png new file mode 100644 index 0000000..818d7f7 Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewTopRightShadow.png differ diff --git a/static/Resources/CPImageView/CPImageViewTopShadow.png b/static/Resources/CPImageView/CPImageViewTopShadow.png new file mode 100644 index 0000000..bb61c1e Binary files /dev/null and b/static/Resources/CPImageView/CPImageViewTopShadow.png differ diff --git a/static/Resources/CPMenuItem/CPMenuItemOnState.png b/static/Resources/CPMenuItem/CPMenuItemOnState.png new file mode 100644 index 0000000..102f335 Binary files /dev/null and b/static/Resources/CPMenuItem/CPMenuItemOnState.png differ diff --git a/static/Resources/CPMenuItem/CPMenuItemOnStateHighlighted.png b/static/Resources/CPMenuItem/CPMenuItemOnStateHighlighted.png new file mode 100644 index 0000000..116fe05 Binary files /dev/null and b/static/Resources/CPMenuItem/CPMenuItemOnStateHighlighted.png differ diff --git a/static/Resources/CPPopUpButton/CPPopUpButtonArrows.png b/static/Resources/CPPopUpButton/CPPopUpButtonArrows.png new file mode 100644 index 0000000..018dd44 Binary files /dev/null and b/static/Resources/CPPopUpButton/CPPopUpButtonArrows.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBarBarRegular.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBarBarRegular.png new file mode 100644 index 0000000..df41776 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBarBarRegular.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBarHUDBarSmall.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBarHUDBarSmall.png new file mode 100644 index 0000000..670fae0 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBarHUDBarSmall.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular0.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular0.png new file mode 100644 index 0000000..b7b8ecd Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular0.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular1.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular1.png new file mode 100644 index 0000000..cb83525 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular1.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular2.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular2.png new file mode 100644 index 0000000..5be2d77 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderBarRegular2.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall0.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall0.png new file mode 100644 index 0000000..113dbb5 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall0.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall1.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall1.png new file mode 100644 index 0000000..0685591 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall1.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall2.png b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall2.png new file mode 100644 index 0000000..04756d6 Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorBezelBorderHUDBarSmall2.png differ diff --git a/static/Resources/CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif b/static/Resources/CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif new file mode 100644 index 0000000..0d2567c Binary files /dev/null and b/static/Resources/CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif differ diff --git a/static/Resources/CPScroller/CPScrollerDecrementArrowHorizontalRegular.png b/static/Resources/CPScroller/CPScrollerDecrementArrowHorizontalRegular.png new file mode 100644 index 0000000..9ab26e2 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerDecrementArrowHorizontalRegular.png differ diff --git a/static/Resources/CPScroller/CPScrollerDecrementArrowHorizontalRegularHighlighted.png b/static/Resources/CPScroller/CPScrollerDecrementArrowHorizontalRegularHighlighted.png new file mode 100644 index 0000000..3fa5fe9 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerDecrementArrowHorizontalRegularHighlighted.png differ diff --git a/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalRegular.png b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalRegular.png new file mode 100644 index 0000000..6421e74 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalRegular.png differ diff --git a/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalRegularHighlighted.png b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalRegularHighlighted.png new file mode 100644 index 0000000..e964cfd Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalRegularHighlighted.png differ diff --git a/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalSmall.png b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalSmall.png new file mode 100644 index 0000000..4fd954e Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalSmall.png differ diff --git a/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalSmallHighlighted.png b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalSmallHighlighted.png new file mode 100644 index 0000000..71f5c96 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerDecrementArrowVerticalSmallHighlighted.png differ diff --git a/static/Resources/CPScroller/CPScrollerIncrementArrowHorizontalRegular.png b/static/Resources/CPScroller/CPScrollerIncrementArrowHorizontalRegular.png new file mode 100644 index 0000000..3e42fd3 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerIncrementArrowHorizontalRegular.png differ diff --git a/static/Resources/CPScroller/CPScrollerIncrementArrowHorizontalRegularHighlighted.png b/static/Resources/CPScroller/CPScrollerIncrementArrowHorizontalRegularHighlighted.png new file mode 100644 index 0000000..9178619 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerIncrementArrowHorizontalRegularHighlighted.png differ diff --git a/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalRegular.png b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalRegular.png new file mode 100644 index 0000000..fc028f3 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalRegular.png differ diff --git a/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalRegularHighlighted.png b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalRegularHighlighted.png new file mode 100644 index 0000000..13006d9 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalRegularHighlighted.png differ diff --git a/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalSmall.png b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalSmall.png new file mode 100644 index 0000000..21032b6 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalSmall.png differ diff --git a/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalSmallHighlighted.png b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalSmallHighlighted.png new file mode 100644 index 0000000..76b7755 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerIncrementArrowVerticalSmallHighlighted.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular0.png b/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular0.png new file mode 100644 index 0000000..52de3ba Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular0.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular1.png b/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular1.png new file mode 100644 index 0000000..25045c1 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular1.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular2.png b/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular2.png new file mode 100644 index 0000000..913b0d9 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobHorizontalRegular2.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobSlotHorizontalRegular.png b/static/Resources/CPScroller/CPScrollerKnobSlotHorizontalRegular.png new file mode 100644 index 0000000..60c5300 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobSlotHorizontalRegular.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobSlotVerticalRegular.png b/static/Resources/CPScroller/CPScrollerKnobSlotVerticalRegular.png new file mode 100644 index 0000000..8dff137 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobSlotVerticalRegular.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobSlotVerticalSmall.png b/static/Resources/CPScroller/CPScrollerKnobSlotVerticalSmall.png new file mode 100644 index 0000000..181b1de Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobSlotVerticalSmall.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobVerticalRegular0.png b/static/Resources/CPScroller/CPScrollerKnobVerticalRegular0.png new file mode 100644 index 0000000..3ddbaca Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobVerticalRegular0.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobVerticalRegular1.png b/static/Resources/CPScroller/CPScrollerKnobVerticalRegular1.png new file mode 100644 index 0000000..c6b874e Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobVerticalRegular1.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobVerticalRegular2.png b/static/Resources/CPScroller/CPScrollerKnobVerticalRegular2.png new file mode 100644 index 0000000..2100b99 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobVerticalRegular2.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobVerticalSmall0.png b/static/Resources/CPScroller/CPScrollerKnobVerticalSmall0.png new file mode 100644 index 0000000..2c1ccc1 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobVerticalSmall0.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobVerticalSmall1.png b/static/Resources/CPScroller/CPScrollerKnobVerticalSmall1.png new file mode 100644 index 0000000..534c519 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobVerticalSmall1.png differ diff --git a/static/Resources/CPScroller/CPScrollerKnobVerticalSmall2.png b/static/Resources/CPScroller/CPScrollerKnobVerticalSmall2.png new file mode 100644 index 0000000..a6aa8d5 Binary files /dev/null and b/static/Resources/CPScroller/CPScrollerKnobVerticalSmall2.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyBottom.png b/static/Resources/CPShadowView/CPShadowViewHeavyBottom.png new file mode 100644 index 0000000..8b3313d Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyBottom.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyBottomLeft.png b/static/Resources/CPShadowView/CPShadowViewHeavyBottomLeft.png new file mode 100644 index 0000000..f4d8065 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyBottomLeft.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyBottomRight.png b/static/Resources/CPShadowView/CPShadowViewHeavyBottomRight.png new file mode 100644 index 0000000..77718b1 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyBottomRight.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyLeft.png b/static/Resources/CPShadowView/CPShadowViewHeavyLeft.png new file mode 100644 index 0000000..8a3e888 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyLeft.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyRight.png b/static/Resources/CPShadowView/CPShadowViewHeavyRight.png new file mode 100644 index 0000000..99ea883 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyRight.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyTop.png b/static/Resources/CPShadowView/CPShadowViewHeavyTop.png new file mode 100644 index 0000000..25c178e Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyTop.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyTopLeft.png b/static/Resources/CPShadowView/CPShadowViewHeavyTopLeft.png new file mode 100644 index 0000000..4915d52 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyTopLeft.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewHeavyTopRight.png b/static/Resources/CPShadowView/CPShadowViewHeavyTopRight.png new file mode 100644 index 0000000..2302e9e Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewHeavyTopRight.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightBottom.png b/static/Resources/CPShadowView/CPShadowViewLightBottom.png new file mode 100644 index 0000000..5fc3ef0 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightBottom.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightBottomLeft.png b/static/Resources/CPShadowView/CPShadowViewLightBottomLeft.png new file mode 100644 index 0000000..654ef3c Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightBottomLeft.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightBottomRight.png b/static/Resources/CPShadowView/CPShadowViewLightBottomRight.png new file mode 100644 index 0000000..93780f2 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightBottomRight.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightLeft.png b/static/Resources/CPShadowView/CPShadowViewLightLeft.png new file mode 100644 index 0000000..d0f29b7 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightLeft.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightRight.png b/static/Resources/CPShadowView/CPShadowViewLightRight.png new file mode 100644 index 0000000..1b3cf77 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightRight.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightTop.png b/static/Resources/CPShadowView/CPShadowViewLightTop.png new file mode 100644 index 0000000..bf630ff Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightTop.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightTopLeft.png b/static/Resources/CPShadowView/CPShadowViewLightTopLeft.png new file mode 100644 index 0000000..2330564 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightTopLeft.png differ diff --git a/static/Resources/CPShadowView/CPShadowViewLightTopRight.png b/static/Resources/CPShadowView/CPShadowViewLightTopRight.png new file mode 100644 index 0000000..818d7f7 Binary files /dev/null and b/static/Resources/CPShadowView/CPShadowViewLightTopRight.png differ diff --git a/static/Resources/CPSlider/CPSliderKnobRegular.png b/static/Resources/CPSlider/CPSliderKnobRegular.png new file mode 100644 index 0000000..f2c3923 Binary files /dev/null and b/static/Resources/CPSlider/CPSliderKnobRegular.png differ diff --git a/static/Resources/CPSlider/CPSliderKnobRegularPushed.png b/static/Resources/CPSlider/CPSliderKnobRegularPushed.png new file mode 100644 index 0000000..b6612ec Binary files /dev/null and b/static/Resources/CPSlider/CPSliderKnobRegularPushed.png differ diff --git a/static/Resources/CPSlider/CPSliderTrackHorizontalCenter.png b/static/Resources/CPSlider/CPSliderTrackHorizontalCenter.png new file mode 100644 index 0000000..db14d24 Binary files /dev/null and b/static/Resources/CPSlider/CPSliderTrackHorizontalCenter.png differ diff --git a/static/Resources/CPSlider/CPSliderTrackHorizontalLeft.png b/static/Resources/CPSlider/CPSliderTrackHorizontalLeft.png new file mode 100644 index 0000000..e2a9b81 Binary files /dev/null and b/static/Resources/CPSlider/CPSliderTrackHorizontalLeft.png differ diff --git a/static/Resources/CPSlider/CPSliderTrackHorizontalRight.png b/static/Resources/CPSlider/CPSliderTrackHorizontalRight.png new file mode 100644 index 0000000..5d4f890 Binary files /dev/null and b/static/Resources/CPSlider/CPSliderTrackHorizontalRight.png differ diff --git a/static/Resources/CPTabView/CPTabViewBezelBackgroundCenter.png b/static/Resources/CPTabView/CPTabViewBezelBackgroundCenter.png new file mode 100644 index 0000000..82bbfbf Binary files /dev/null and b/static/Resources/CPTabView/CPTabViewBezelBackgroundCenter.png differ diff --git a/static/Resources/CPTabView/CPTabViewBezelBorder.png b/static/Resources/CPTabView/CPTabViewBezelBorder.png new file mode 100644 index 0000000..4fc4179 Binary files /dev/null and b/static/Resources/CPTabView/CPTabViewBezelBorder.png differ diff --git a/static/Resources/CPTabView/CPTabViewBezelBorderLeft.png b/static/Resources/CPTabView/CPTabViewBezelBorderLeft.png new file mode 100644 index 0000000..a4ae8cf Binary files /dev/null and b/static/Resources/CPTabView/CPTabViewBezelBorderLeft.png differ diff --git a/static/Resources/CPTabView/CPTabViewBezelBorderRight.png b/static/Resources/CPTabView/CPTabViewBezelBorderRight.png new file mode 100644 index 0000000..a253771 Binary files /dev/null and b/static/Resources/CPTabView/CPTabViewBezelBorderRight.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelBackgroundCenter.png b/static/Resources/CPTabView/_CPTabLabelBackgroundCenter.png new file mode 100644 index 0000000..7436399 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelBackgroundCenter.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelBackgroundLeft.png b/static/Resources/CPTabView/_CPTabLabelBackgroundLeft.png new file mode 100644 index 0000000..5a0edfc Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelBackgroundLeft.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelBackgroundRight.png b/static/Resources/CPTabView/_CPTabLabelBackgroundRight.png new file mode 100644 index 0000000..381d414 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelBackgroundRight.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelSelectedCenter.png b/static/Resources/CPTabView/_CPTabLabelSelectedCenter.png new file mode 100644 index 0000000..9fe8023 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelSelectedCenter.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelSelectedLeft.png b/static/Resources/CPTabView/_CPTabLabelSelectedLeft.png new file mode 100644 index 0000000..3c0d4a1 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelSelectedLeft.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelSelectedRight.png b/static/Resources/CPTabView/_CPTabLabelSelectedRight.png new file mode 100644 index 0000000..3388ca8 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelSelectedRight.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelsViewCenter.png b/static/Resources/CPTabView/_CPTabLabelsViewCenter.png new file mode 100644 index 0000000..19d8e74 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelsViewCenter.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelsViewLeft.png b/static/Resources/CPTabView/_CPTabLabelsViewLeft.png new file mode 100644 index 0000000..348cfb9 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelsViewLeft.png differ diff --git a/static/Resources/CPTabView/_CPTabLabelsViewRight.png b/static/Resources/CPTabView/_CPTabLabelsViewRight.png new file mode 100644 index 0000000..b9973d4 Binary files /dev/null and b/static/Resources/CPTabView/_CPTabLabelsViewRight.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare0.png b/static/Resources/CPTextField/CPTextFieldBezelSquare0.png new file mode 100644 index 0000000..1819bb3 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare0.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare1.png b/static/Resources/CPTextField/CPTextFieldBezelSquare1.png new file mode 100644 index 0000000..2c77bb7 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare1.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare2.png b/static/Resources/CPTextField/CPTextFieldBezelSquare2.png new file mode 100644 index 0000000..848e1da Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare2.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare3.png b/static/Resources/CPTextField/CPTextFieldBezelSquare3.png new file mode 100644 index 0000000..81cd274 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare3.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare4.png b/static/Resources/CPTextField/CPTextFieldBezelSquare4.png new file mode 100644 index 0000000..9432d30 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare4.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare5.png b/static/Resources/CPTextField/CPTextFieldBezelSquare5.png new file mode 100644 index 0000000..21f8100 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare5.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare6.png b/static/Resources/CPTextField/CPTextFieldBezelSquare6.png new file mode 100644 index 0000000..acc67df Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare6.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare7.png b/static/Resources/CPTextField/CPTextFieldBezelSquare7.png new file mode 100644 index 0000000..0c228f1 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare7.png differ diff --git a/static/Resources/CPTextField/CPTextFieldBezelSquare8.png b/static/Resources/CPTextField/CPTextFieldBezelSquare8.png new file mode 100644 index 0000000..07f2197 Binary files /dev/null and b/static/Resources/CPTextField/CPTextFieldBezelSquare8.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow0.png b/static/Resources/CPWindow/CPWindowShadow0.png new file mode 100644 index 0000000..d47d315 Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow0.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow1.png b/static/Resources/CPWindow/CPWindowShadow1.png new file mode 100644 index 0000000..fc74aea Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow1.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow2.png b/static/Resources/CPWindow/CPWindowShadow2.png new file mode 100644 index 0000000..9764d1b Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow2.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow3.png b/static/Resources/CPWindow/CPWindowShadow3.png new file mode 100644 index 0000000..4565f2b Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow3.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow4.png b/static/Resources/CPWindow/CPWindowShadow4.png new file mode 100644 index 0000000..d61c0f3 Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow4.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow5.png b/static/Resources/CPWindow/CPWindowShadow5.png new file mode 100644 index 0000000..f32d20b Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow5.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow6.png b/static/Resources/CPWindow/CPWindowShadow6.png new file mode 100644 index 0000000..5208801 Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow6.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow7.png b/static/Resources/CPWindow/CPWindowShadow7.png new file mode 100644 index 0000000..c3a00f6 Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow7.png differ diff --git a/static/Resources/CPWindow/CPWindowShadow8.png b/static/Resources/CPWindow/CPWindowShadow8.png new file mode 100644 index 0000000..5f007de Binary files /dev/null and b/static/Resources/CPWindow/CPWindowShadow8.png differ diff --git a/static/Resources/CPWindowResizeIndicator.png b/static/Resources/CPWindowResizeIndicator.png new file mode 100644 index 0000000..6773128 Binary files /dev/null and b/static/Resources/CPWindowResizeIndicator.png differ diff --git a/static/Resources/FIXME_ImageShadow.png b/static/Resources/FIXME_ImageShadow.png new file mode 100644 index 0000000..f544c24 Binary files /dev/null and b/static/Resources/FIXME_ImageShadow.png differ diff --git a/static/Resources/HUDTheme/WindowBottomCenter.png b/static/Resources/HUDTheme/WindowBottomCenter.png new file mode 100644 index 0000000..ca64f73 Binary files /dev/null and b/static/Resources/HUDTheme/WindowBottomCenter.png differ diff --git a/static/Resources/HUDTheme/WindowBottomLeft.png b/static/Resources/HUDTheme/WindowBottomLeft.png new file mode 100644 index 0000000..521b7c6 Binary files /dev/null and b/static/Resources/HUDTheme/WindowBottomLeft.png differ diff --git a/static/Resources/HUDTheme/WindowBottomRight.png b/static/Resources/HUDTheme/WindowBottomRight.png new file mode 100644 index 0000000..ac800b0 Binary files /dev/null and b/static/Resources/HUDTheme/WindowBottomRight.png differ diff --git a/static/Resources/HUDTheme/WindowCenter.png b/static/Resources/HUDTheme/WindowCenter.png new file mode 100644 index 0000000..5b9ae35 Binary files /dev/null and b/static/Resources/HUDTheme/WindowCenter.png differ diff --git a/static/Resources/HUDTheme/WindowCenterLeft.png b/static/Resources/HUDTheme/WindowCenterLeft.png new file mode 100644 index 0000000..4d6b63f Binary files /dev/null and b/static/Resources/HUDTheme/WindowCenterLeft.png differ diff --git a/static/Resources/HUDTheme/WindowCenterRight.png b/static/Resources/HUDTheme/WindowCenterRight.png new file mode 100644 index 0000000..750eb71 Binary files /dev/null and b/static/Resources/HUDTheme/WindowCenterRight.png differ diff --git a/static/Resources/HUDTheme/WindowClose.png b/static/Resources/HUDTheme/WindowClose.png new file mode 100644 index 0000000..0f45a70 Binary files /dev/null and b/static/Resources/HUDTheme/WindowClose.png differ diff --git a/static/Resources/HUDTheme/WindowCloseActive.png b/static/Resources/HUDTheme/WindowCloseActive.png new file mode 100644 index 0000000..94771fc Binary files /dev/null and b/static/Resources/HUDTheme/WindowCloseActive.png differ diff --git a/static/Resources/HUDTheme/WindowTopCenter.png b/static/Resources/HUDTheme/WindowTopCenter.png new file mode 100644 index 0000000..0b89f1b Binary files /dev/null and b/static/Resources/HUDTheme/WindowTopCenter.png differ diff --git a/static/Resources/HUDTheme/WindowTopLeft.png b/static/Resources/HUDTheme/WindowTopLeft.png new file mode 100644 index 0000000..290db92 Binary files /dev/null and b/static/Resources/HUDTheme/WindowTopLeft.png differ diff --git a/static/Resources/HUDTheme/WindowTopRight.png b/static/Resources/HUDTheme/WindowTopRight.png new file mode 100644 index 0000000..dbb8e39 Binary files /dev/null and b/static/Resources/HUDTheme/WindowTopRight.png differ diff --git a/static/Resources/_CPMenuBarWindow/_CPMenuBarWindowBackground.png b/static/Resources/_CPMenuBarWindow/_CPMenuBarWindowBackground.png new file mode 100644 index 0000000..3938049 Binary files /dev/null and b/static/Resources/_CPMenuBarWindow/_CPMenuBarWindowBackground.png differ diff --git a/static/Resources/_CPMenuItemView/_CPMenuItemViewMenuBarArrow.png b/static/Resources/_CPMenuItemView/_CPMenuItemViewMenuBarArrow.png new file mode 100644 index 0000000..27ac7e0 Binary files /dev/null and b/static/Resources/_CPMenuItemView/_CPMenuItemViewMenuBarArrow.png differ diff --git a/static/Resources/_CPMenuItemView/_CPMenuItemViewMenuBarArrowActivated.png b/static/Resources/_CPMenuItemView/_CPMenuItemViewMenuBarArrowActivated.png new file mode 100644 index 0000000..33dc63b Binary files /dev/null and b/static/Resources/_CPMenuItemView/_CPMenuItemViewMenuBarArrowActivated.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindow1.png b/static/Resources/_CPMenuWindow/_CPMenuWindow1.png new file mode 100644 index 0000000..438f284 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindow1.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindow3.png b/static/Resources/_CPMenuWindow/_CPMenuWindow3.png new file mode 100644 index 0000000..52efc8f Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindow3.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindow4.png b/static/Resources/_CPMenuWindow/_CPMenuWindow4.png new file mode 100644 index 0000000..0b952a9 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindow4.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindow5.png b/static/Resources/_CPMenuWindow/_CPMenuWindow5.png new file mode 100644 index 0000000..a9a7257 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindow5.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindow7.png b/static/Resources/_CPMenuWindow/_CPMenuWindow7.png new file mode 100644 index 0000000..c577e8b Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindow7.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindowMoreAbove.png b/static/Resources/_CPMenuWindow/_CPMenuWindowMoreAbove.png new file mode 100644 index 0000000..1058cb9 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindowMoreAbove.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindowMoreBelow.png b/static/Resources/_CPMenuWindow/_CPMenuWindowMoreBelow.png new file mode 100644 index 0000000..bbaca54 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindowMoreBelow.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindowRounded0.png b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded0.png new file mode 100644 index 0000000..0892087 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded0.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindowRounded2.png b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded2.png new file mode 100644 index 0000000..dd79b1e Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded2.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindowRounded6.png b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded6.png new file mode 100644 index 0000000..e0846a6 Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded6.png differ diff --git a/static/Resources/_CPMenuWindow/_CPMenuWindowRounded8.png b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded8.png new file mode 100644 index 0000000..3cff81e Binary files /dev/null and b/static/Resources/_CPMenuWindow/_CPMenuWindowRounded8.png differ diff --git a/static/Resources/_CPToolbarView/_CPToolbarViewBackground.png b/static/Resources/_CPToolbarView/_CPToolbarViewBackground.png new file mode 100644 index 0000000..ce3d592 Binary files /dev/null and b/static/Resources/_CPToolbarView/_CPToolbarViewBackground.png differ diff --git a/static/Resources/_CPToolbarView/_CPToolbarViewExtraItemsAlternateImage.png b/static/Resources/_CPToolbarView/_CPToolbarViewExtraItemsAlternateImage.png new file mode 100644 index 0000000..a73d137 Binary files /dev/null and b/static/Resources/_CPToolbarView/_CPToolbarViewExtraItemsAlternateImage.png differ diff --git a/static/Resources/_CPToolbarView/_CPToolbarViewExtraItemsImage.png b/static/Resources/_CPToolbarView/_CPToolbarViewExtraItemsImage.png new file mode 100644 index 0000000..5182b38 Binary files /dev/null and b/static/Resources/_CPToolbarView/_CPToolbarViewExtraItemsImage.png differ diff --git a/static/Resources/_CPWindowView/_CPWindowViewResizeIndicator.png b/static/Resources/_CPWindowView/_CPWindowViewResizeIndicator.png new file mode 100644 index 0000000..6773128 Binary files /dev/null and b/static/Resources/_CPWindowView/_CPWindowViewResizeIndicator.png differ diff --git a/static/Resources/brightness_bar.png b/static/Resources/brightness_bar.png new file mode 100644 index 0000000..95898fe Binary files /dev/null and b/static/Resources/brightness_bar.png differ diff --git a/static/Resources/color_well.png b/static/Resources/color_well.png new file mode 100644 index 0000000..54444a6 Binary files /dev/null and b/static/Resources/color_well.png differ diff --git a/static/Resources/kuler_button.png b/static/Resources/kuler_button.png new file mode 100644 index 0000000..bd766c4 Binary files /dev/null and b/static/Resources/kuler_button.png differ diff --git a/static/Resources/kuler_button_h.png b/static/Resources/kuler_button_h.png new file mode 100644 index 0000000..84b2866 Binary files /dev/null and b/static/Resources/kuler_button_h.png differ diff --git a/static/Resources/slider_button.png b/static/Resources/slider_button.png new file mode 100644 index 0000000..aea0e9e Binary files /dev/null and b/static/Resources/slider_button.png differ diff --git a/static/Resources/slider_button_h.png b/static/Resources/slider_button_h.png new file mode 100644 index 0000000..3309cec Binary files /dev/null and b/static/Resources/slider_button_h.png differ diff --git a/static/Resources/wheel.png b/static/Resources/wheel.png new file mode 100644 index 0000000..939a9eb Binary files /dev/null and b/static/Resources/wheel.png differ diff --git a/static/Resources/wheel_black.png b/static/Resources/wheel_black.png new file mode 100644 index 0000000..822ec95 Binary files /dev/null and b/static/Resources/wheel_black.png differ diff --git a/static/Resources/wheel_button.png b/static/Resources/wheel_button.png new file mode 100644 index 0000000..02f420f Binary files /dev/null and b/static/Resources/wheel_button.png differ diff --git a/static/Resources/wheel_button_h.png b/static/Resources/wheel_button_h.png new file mode 100644 index 0000000..a6fc155 Binary files /dev/null and b/static/Resources/wheel_button_h.png differ diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index f0c2529..5527c25 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,93 +1,108 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" import "WLHTMLTextField.j" @implementation WLWebResultsView : WLResultsView { + BOOL _includeDelcious; +} + +-(id)initWithFrame: (CPRect)aFrame { + self = [super initWithFrame:aFrame]; + _includeDelicious = NO; + return self; +} + +-(void)setIncludeDelicious: (BOOL)aBool { + _includeDelicious = aBool; +} + +-(BOOL)includeDelicious { + return _includeDelicious; } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(325,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { - var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset; + var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset+"&includeDelicious="+[self includeDelicious]; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; frame = CGRectMake(5,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setSelectable:YES]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setSelectable:YES]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } @end
lethain/mahou
873d5f0989b2c7194bcaa338535119b6c6112181
Toggling about window properly.
diff --git a/static/AppController.j b/static/AppController.j index 549c125..a68d38d 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,245 +1,251 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLResultsView.j" import "WLImageResultsView.j" import "WLWebResultsView.j" import "WLNewsResultsView.j" import "WLURLLabel.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; CPView webView; CPView imageView; CPView newsView; CPWindow aboutWindow; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { CPLogRegister(CPLogConsole); var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; + [self setupAboutWindow]; [theWindow orderFront:self]; [self setupMainMenu]; [CPMenu setMenuBarVisible:YES]; } -(void)search: (id)sender { var selectedItem = [tabView selectedTabViewItem]; var selectedView = [selectedItem view]; [selectedView searchFor:[searchField stringValue]]; } -(void)tabView:(CPTabView)aTabView didSelectTabViewItem: (CPTabViewItem)anItem { if ([[searchField stringValue] length] > 0) { [self search:self]; } } -(void)setupMainMenu { var m = [[CPMenu alloc] initWithTitle:@"MainMenu"]; [[CPApplication sharedApplication] setMainMenu:m]; // Web Menu var webMenuItem = [[CPMenuItem alloc] initWithTitle:@"Web" action:@selector(doNothing:) keyEquivalent:@"W"]; [m addItem:webMenuItem]; var imageMenuItem = [[CPMenuItem alloc] initWithTitle:@"Image" action:@selector(doNothing:) keyEquivalent:@"I"]; [m addItem:imageMenuItem]; var newsMenuItem = [[CPMenuItem alloc] initWithTitle:@"News" action:@selector(doNothing:) keyEquivalent:@"N"]; [m addItem:newsMenuItem]; [m addItem:[CPMenuItem separatorItem]]; - var aboutMenuItem = [[CPMenuItem alloc] initWithTitle:@"About" action:@selector(aboutWindow:) keyEquivalent:@"A"]; + var aboutMenuItem = [[CPMenuItem alloc] initWithTitle:@"About" action:@selector(toggleAboutWindow:) keyEquivalent:@"A"]; [m addItem:aboutMenuItem]; } -(void)doNothing:(id)sender { alert("blah"); } --(void)aboutWindow:(id)sender { +-(void)toggleAboutWindow:(id)sender { + if ([aboutWindow isVisible]==YES) { + [aboutWindow orderOut:self]; + } + else { + [aboutWindow orderFront:self]; + } +} + +-(void)setupAboutWindow { - var mainWindow = [[CPApplication sharedApplication] mainWindow]; - var bounds = [mainWindow bounds]; + //var mainWindow = [[CPApplication sharedApplication] mainWindow]; + //var bounds = [mainWindow bounds]; var frame = CGRectMake(150,150,300,200); - var window = [[CPWindow alloc] initWithContentRect:frame styleMask:CPClosableWindowMask|CPTitledWindowMask|CPHUDBackgroundWindowMask]; - [window setTitle:@"About Mahou"]; + var aboutWindow = [[CPWindow alloc] initWithContentRect:frame styleMask:CPClosableWindowMask|CPTitledWindowMask|CPHUDBackgroundWindowMask]; + [aboutWindow setTitle:@"About Mahou"]; - var contentView = [window contentView]; + var contentView = [aboutWindow contentView]; var titleLabel = [self makeURLLabelWith:@"Will Larson (http://lethain.com/)" andUrl:@"http://lethain.com/" at:CPRectMake(0,0,300,30)]; [titleLabel setTextColor:[CPColor lightGrayColor]]; [titleLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [titleLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:titleLabel]; var uLabel = [self makeLabelWith:@"Made using" at:CPRectMake(0,30,300,30)]; [uLabel setTextColor:[CPColor whiteColor]]; [uLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [uLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:uLabel]; var cLabel = [self makeURLLabelWith:@"Cappuccino" andUrl:@"http://cappuccino.org/" at:CPRectMake(0,60,300,30)]; [cLabel setTextColor:[CPColor blueColor]]; [cLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [cLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:cLabel]; var yLabel = [self makeURLLabelWith:@"Yahoo! BOSS" andUrl:@"http://developer.yahoo.com/search/boss/" at:CPRectMake(0,90,300,30)]; [yLabel setTextColor:[CPColor blueColor]]; [yLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [yLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:yLabel]; var gLabel = [self makeURLLabelWith:@"Google App Engine" andUrl:@"http://code.google.com/appengine/" at:CPRectMake(0,120,300,30)]; [gLabel setTextColor:[CPColor blueColor]]; [gLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; [gLabel setAlignment:CPCenterTextAlignment]; [contentView addSubview:gLabel]; - - - [window orderFront:self]; - } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; [tabView setTabViewType:CPTopTabsBezelBorder]; [contentView addSubview:tabView]; //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; webView = [[WLWebResultsView alloc] initWithFrame:frame]; imageView = [[WLImageResultsView alloc] initWithFrame:frame]; newsView = [[WLNewsResultsView alloc] initWithFrame:frame]; [webSearchTabItem setLabel:@"Web"]; [imageSearchTabItem setLabel:@"Image"]; [newsSearchTabItem setLabel:@"News"]; [webSearchTabItem setView:webView]; [imageSearchTabItem setView:imageView]; [newsSearchTabItem setView:newsView]; [tabView addTabViewItem:webSearchTabItem]; [tabView addTabViewItem:imageSearchTabItem]; [tabView addTabViewItem:newsSearchTabItem]; //[tabView selectTabViewItem:imageSearchTabItem]; [tabView setDelegate:self]; } @end
lethain/mahou
d81517c348556acfc121636193fdab86998b0518
About window functioning.
diff --git a/static/AppController.j b/static/AppController.j index d8d4440..549c125 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,144 +1,245 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLResultsView.j" import "WLImageResultsView.j" import "WLWebResultsView.j" import "WLNewsResultsView.j" +import "WLURLLabel.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; CPView webView; CPView imageView; CPView newsView; + CPWindow aboutWindow; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { CPLogRegister(CPLogConsole); var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; [theWindow orderFront:self]; - //[CPMenu setMenuBarVisible:YES]; + [self setupMainMenu]; + [CPMenu setMenuBarVisible:YES]; + } -(void)search: (id)sender { var selectedItem = [tabView selectedTabViewItem]; var selectedView = [selectedItem view]; [selectedView searchFor:[searchField stringValue]]; } -(void)tabView:(CPTabView)aTabView didSelectTabViewItem: (CPTabViewItem)anItem { if ([[searchField stringValue] length] > 0) { [self search:self]; } } +-(void)setupMainMenu { + var m = [[CPMenu alloc] initWithTitle:@"MainMenu"]; + [[CPApplication sharedApplication] setMainMenu:m]; + + + // Web Menu + var webMenuItem = [[CPMenuItem alloc] initWithTitle:@"Web" action:@selector(doNothing:) keyEquivalent:@"W"]; + [m addItem:webMenuItem]; + + + var imageMenuItem = [[CPMenuItem alloc] initWithTitle:@"Image" action:@selector(doNothing:) keyEquivalent:@"I"]; + [m addItem:imageMenuItem]; + + + var newsMenuItem = [[CPMenuItem alloc] initWithTitle:@"News" action:@selector(doNothing:) keyEquivalent:@"N"]; + [m addItem:newsMenuItem]; + + + [m addItem:[CPMenuItem separatorItem]]; + var aboutMenuItem = [[CPMenuItem alloc] initWithTitle:@"About" action:@selector(aboutWindow:) keyEquivalent:@"A"]; + + [m addItem:aboutMenuItem]; + + +} + +-(void)doNothing:(id)sender { + alert("blah"); +} + +-(void)aboutWindow:(id)sender { + + + var mainWindow = [[CPApplication sharedApplication] mainWindow]; + var bounds = [mainWindow bounds]; + + var frame = CGRectMake(150,150,300,200); + var window = [[CPWindow alloc] initWithContentRect:frame styleMask:CPClosableWindowMask|CPTitledWindowMask|CPHUDBackgroundWindowMask]; + [window setTitle:@"About Mahou"]; + + + var contentView = [window contentView]; + + + var titleLabel = [self makeURLLabelWith:@"Will Larson (http://lethain.com/)" andUrl:@"http://lethain.com/" at:CPRectMake(0,0,300,30)]; + [titleLabel setTextColor:[CPColor lightGrayColor]]; + [titleLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; + [titleLabel setAlignment:CPCenterTextAlignment]; + [contentView addSubview:titleLabel]; + + var uLabel = [self makeLabelWith:@"Made using" at:CPRectMake(0,30,300,30)]; + [uLabel setTextColor:[CPColor whiteColor]]; + [uLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; + [uLabel setAlignment:CPCenterTextAlignment]; + [contentView addSubview:uLabel]; + + + var cLabel = [self makeURLLabelWith:@"Cappuccino" andUrl:@"http://cappuccino.org/" at:CPRectMake(0,60,300,30)]; + [cLabel setTextColor:[CPColor blueColor]]; + [cLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; + [cLabel setAlignment:CPCenterTextAlignment]; + [contentView addSubview:cLabel]; + + var yLabel = [self makeURLLabelWith:@"Yahoo! BOSS" andUrl:@"http://developer.yahoo.com/search/boss/" at:CPRectMake(0,90,300,30)]; + [yLabel setTextColor:[CPColor blueColor]]; + [yLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; + [yLabel setAlignment:CPCenterTextAlignment]; + [contentView addSubview:yLabel]; + + var gLabel = [self makeURLLabelWith:@"Google App Engine" andUrl:@"http://code.google.com/appengine/" at:CPRectMake(0,120,300,30)]; + [gLabel setTextColor:[CPColor blueColor]]; + [gLabel setFont:[CPFont boldSystemFontOfSize:16.0]]; + [gLabel setAlignment:CPCenterTextAlignment]; + [contentView addSubview:gLabel]; + + + [window orderFront:self]; + +} + +-(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { + var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setStringValue:aString]; + [field setAutoresizingMask: CPViewWidthSizable]; + return field; +} + +-(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { + var field = [[WLURLLabel alloc] initWithFrame:aFrame]; + [field setUrl:aURL]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setStringValue:aString]; + [field setAutoresizingMask: CPViewWidthSizable]; + return field; +} + -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; [tabView setTabViewType:CPTopTabsBezelBorder]; [contentView addSubview:tabView]; //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; webView = [[WLWebResultsView alloc] initWithFrame:frame]; imageView = [[WLImageResultsView alloc] initWithFrame:frame]; newsView = [[WLNewsResultsView alloc] initWithFrame:frame]; [webSearchTabItem setLabel:@"Web"]; [imageSearchTabItem setLabel:@"Image"]; [newsSearchTabItem setLabel:@"News"]; [webSearchTabItem setView:webView]; [imageSearchTabItem setView:imageView]; [newsSearchTabItem setView:newsView]; [tabView addTabViewItem:webSearchTabItem]; [tabView addTabViewItem:imageSearchTabItem]; [tabView addTabViewItem:newsSearchTabItem]; //[tabView selectTabViewItem:imageSearchTabItem]; [tabView setDelegate:self]; } @end diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index 88c77f7..f0c2529 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,91 +1,93 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" import "WLHTMLTextField.j" @implementation WLWebResultsView : WLResultsView { } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(325,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; frame = CGRectMake(5,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; + [field setSelectable:YES]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; + [field setSelectable:YES]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } @end
lethain/mahou
5696b09bd2e6d1cea090d6165974623da01472f2
Added news functionality.
diff --git a/main.py b/main.py index bde5a42..b6822c8 100755 --- a/main.py +++ b/main.py @@ -1,67 +1,76 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. __author__ = "Vik Singh ([email protected])" import logging import wsgiref.handlers from google.appengine.ext import webapp from yos.crawl.rest import download from yos.util import console from yos.boss import ysearch from yos.yql import db from django.utils import simplejson class ImageSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) data = ysearch.search(query,vertical="images",count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) +class NewsSearchHandler(webapp.RequestHandler): + def get(self): + query = console.strfix(self.request.get("query")) + offset = int(console.strfix(self.request.get("offset"))) + data = ysearch.search(query,vertical="news",count=20,start=offset); + images = db.create(data=data) + serialized = simplejson.dumps(images.rows) + self.response.out.write(serialized) + class WebSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) data = ysearch.search(query,count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) class RootHandler(webapp.RequestHandler): def get(self): self.redirect(ROOT_REDIRECT) def main(): logging.getLogger().setLevel(logging.DEBUG) application = webapp.WSGIApplication([('/', RootHandler), ('/search/images', ImageSearchHandler), ('/search/web', WebSearchHandler), + ('/search/news', NewsSearchHandler), ], - debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() diff --git a/static/AppController.j b/static/AppController.j index e903494..d8d4440 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,143 +1,144 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLResultsView.j" import "WLImageResultsView.j" import "WLWebResultsView.j" +import "WLNewsResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; CPView webView; CPView imageView; CPView newsView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { CPLogRegister(CPLogConsole); var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; [theWindow orderFront:self]; - [CPMenu setMenuBarVisible:YES]; + //[CPMenu setMenuBarVisible:YES]; } -(void)search: (id)sender { var selectedItem = [tabView selectedTabViewItem]; var selectedView = [selectedItem view]; [selectedView searchFor:[searchField stringValue]]; } -(void)tabView:(CPTabView)aTabView didSelectTabViewItem: (CPTabViewItem)anItem { if ([[searchField stringValue] length] > 0) { [self search:self]; } } -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; [tabView setTabViewType:CPTopTabsBezelBorder]; [contentView addSubview:tabView]; //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; webView = [[WLWebResultsView alloc] initWithFrame:frame]; imageView = [[WLImageResultsView alloc] initWithFrame:frame]; - newsView = [[WLResultsView alloc] initWithFrame:frame]; + newsView = [[WLNewsResultsView alloc] initWithFrame:frame]; [webSearchTabItem setLabel:@"Web"]; [imageSearchTabItem setLabel:@"Image"]; [newsSearchTabItem setLabel:@"News"]; [webSearchTabItem setView:webView]; [imageSearchTabItem setView:imageView]; [newsSearchTabItem setView:newsView]; [tabView addTabViewItem:webSearchTabItem]; [tabView addTabViewItem:imageSearchTabItem]; [tabView addTabViewItem:newsSearchTabItem]; //[tabView selectTabViewItem:imageSearchTabItem]; [tabView setDelegate:self]; } @end diff --git a/static/WLNewsResultsView.j b/static/WLNewsResultsView.j new file mode 100644 index 0000000..2eea9d0 --- /dev/null +++ b/static/WLNewsResultsView.j @@ -0,0 +1,30 @@ +import <Foundation/CPObject.j> +import "WLResultsView.j" +import "WLURLLabel.j" +import "WLHTMLTextField.j" +import "WLWebResultsView.j" + +@implementation WLNewsResultsView : WLResultsView { +} + +-(CPSize)_minItemSize { + //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); + return CGSizeMake(325,100); +} + +-(CPSize)_maxItemSize { + //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); + return CGSizeMake(1500,100); +} + +-(CPCollectionViewItem)_itemPrototype { + return [[WebCell alloc] init]; +} + +-(void)_search { + var query = "/search/news?query="+encodeURIComponent(_searchString)+"&offset="+_offset; + var request = [CPURLRequest requestWithURL:query]; + var connection = [CPURLConnection connectionWithRequest:request delegate:self]; + [connection start]; +} +@end
lethain/mahou
012d63a4b4195be0f3b0e8ace6017d6eb3ffdd2d
Aligned url with the title.
diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index 525066c..88c77f7 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,91 +1,91 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" import "WLHTMLTextField.j" @implementation WLWebResultsView : WLResultsView { } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); - return CGSizeMake(300,100); + return CGSizeMake(325,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; - frame = CGRectMake(0,25,CPRectGetWidth(bounds)-75,25); + frame = CGRectMake(5,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } @end
lethain/mahou
4bf4f75292f3a54438957fb8d8f97f758aad0907
Now stripping out unwanted HTML tags from incoming text.
diff --git a/static/WLHTMLTextField.j b/static/WLHTMLTextField.j new file mode 100644 index 0000000..a55caa9 --- /dev/null +++ b/static/WLHTMLTextField.j @@ -0,0 +1,31 @@ +import <Foundation/CPObject.j> +import <AppKit/CPTextField.j> + +WLStripHTML = 0, +WLIgnoreHTML = 1, +WLRepresentHTML = 2; + + +@implementation WLHTMLTextField : CPTextField +{ + int _htmlMode; +} + +-(void)setHTMLMode: (int)anInt { + _htmlMode = anInt; +} + +-(int)htmlMode { + if (!_htmlMode) { + _htmlMode = WLStripHTML; + } + return _htmlMode; +} + +-(void)setStringValue: (CPString)aString { + var mode = [self htmlMode]; + if (mode == WLStripHTML) { + aString = aString.replace(/<\S[^>]*>/g,''); + } + [super setStringValue:aString]; +} diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index 929fa62..525066c 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,90 +1,91 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" +import "WLHTMLTextField.j" @implementation WLWebResultsView : WLResultsView { } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(300,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; frame = CGRectMake(0,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { - var field = [[CPTextField alloc] initWithFrame:aFrame]; + var field = [[WLHTMLTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } @end
lethain/mahou
007d0261b176482faf3e33922a1eb118b04ed021
Moved titles slight away from left line for better readability.
diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j index b3eb3a0..929fa62 100644 --- a/static/WLWebResultsView.j +++ b/static/WLWebResultsView.j @@ -1,90 +1,90 @@ import <Foundation/CPObject.j> import "WLResultsView.j" import "WLURLLabel.j" @implementation WLWebResultsView : WLResultsView { } -(CPSize)_minItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(300,100); } -(CPSize)_maxItemSize { //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); return CGSizeMake(1500,100); } -(CPCollectionViewItem)_itemPrototype { return [[WebCell alloc] init]; } -(void)_search { var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } @end @implementation WebCell : CPCollectionViewItem { CPDictionary dict; CPView webView; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!webView) { webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; [webView setBackgroundColor:[CPColor whiteColor]]; [webView setAutoresizingMask: CPViewWidthSizable]; var bounds = [webView bounds]; - var frame = CGRectMake(0,0,CPRectGetMaxX(bounds),25); + var frame = CGRectMake(5,0,CPRectGetMaxX(bounds)-5,25); var titleLabel = [self makeLabelWith:dict.title at:frame]; [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; [titleLabel setAlignment:CPLeftTextAlignment]; [webView addSubview:titleLabel]; frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); var date = [self makeLabelWith:dict.date at:frame]; [date setAlignment:CPRightTextAlignment]; [webView addSubview:date]; frame = CGRectMake(0,25,CPRectGetWidth(bounds)-75,25); var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; [link setTextColor:[CPColor blueColor]]; [webView addSubview:link]; frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); var abstract = [self makeLabelWith:dict.abstract at:frame]; [abstract setLineBreakMode:CPLineBreakByWordWrapping]; [webView addSubview:abstract]; //[webView addSubiew:[self makeURLLabel]]; //[webView addSubview:[self makeAbstractLabel]]; [self setView:webView]; } } -(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { var field = [[CPTextField alloc] initWithFrame:aFrame]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } -(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { var field = [[WLURLLabel alloc] initWithFrame:aFrame]; [field setUrl:aURL]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setStringValue:aString]; [field setAutoresizingMask: CPViewWidthSizable]; return field; } @end
lethain/mahou
68fd7ddcd46a88fc3710e8862269e2d98813d813
Display web results as well.
diff --git a/main.py b/main.py index 95fb965..bde5a42 100755 --- a/main.py +++ b/main.py @@ -1,57 +1,67 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. __author__ = "Vik Singh ([email protected])" import logging import wsgiref.handlers from google.appengine.ext import webapp from yos.crawl.rest import download from yos.util import console from yos.boss import ysearch from yos.yql import db from django.utils import simplejson class ImageSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) data = ysearch.search(query,vertical="images",count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) + +class WebSearchHandler(webapp.RequestHandler): + def get(self): + query = console.strfix(self.request.get("query")) + offset = int(console.strfix(self.request.get("offset"))) + data = ysearch.search(query,count=20,start=offset); + images = db.create(data=data) + serialized = simplejson.dumps(images.rows) + self.response.out.write(serialized) class RootHandler(webapp.RequestHandler): def get(self): self.redirect(ROOT_REDIRECT) def main(): logging.getLogger().setLevel(logging.DEBUG) application = webapp.WSGIApplication([('/', RootHandler), ('/search/images', ImageSearchHandler), + ('/search/web', WebSearchHandler), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() diff --git a/static/AppController.j b/static/AppController.j index c0d126b..e903494 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,142 +1,143 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLResultsView.j" import "WLImageResultsView.j" +import "WLWebResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; CPView webView; CPView imageView; CPView newsView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { CPLogRegister(CPLogConsole); var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; [theWindow orderFront:self]; [CPMenu setMenuBarVisible:YES]; } -(void)search: (id)sender { var selectedItem = [tabView selectedTabViewItem]; var selectedView = [selectedItem view]; [selectedView searchFor:[searchField stringValue]]; } -(void)tabView:(CPTabView)aTabView didSelectTabViewItem: (CPTabViewItem)anItem { if ([[searchField stringValue] length] > 0) { [self search:self]; } } -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; [tabView setTabViewType:CPTopTabsBezelBorder]; [contentView addSubview:tabView]; //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; - webView = [[WLResultsView alloc] initWithFrame:frame]; + webView = [[WLWebResultsView alloc] initWithFrame:frame]; imageView = [[WLImageResultsView alloc] initWithFrame:frame]; newsView = [[WLResultsView alloc] initWithFrame:frame]; [webSearchTabItem setLabel:@"Web"]; [imageSearchTabItem setLabel:@"Image"]; [newsSearchTabItem setLabel:@"News"]; [webSearchTabItem setView:webView]; [imageSearchTabItem setView:imageView]; [newsSearchTabItem setView:newsView]; [tabView addTabViewItem:webSearchTabItem]; [tabView addTabViewItem:imageSearchTabItem]; [tabView addTabViewItem:newsSearchTabItem]; - [tabView selectTabViewItem:imageSearchTabItem]; + //[tabView selectTabViewItem:imageSearchTabItem]; [tabView setDelegate:self]; } @end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index e8b3690..fd0175d 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,98 +1,81 @@ import <Foundation/CPObject.j> import "WLResultsView.j" @implementation WLImageResultsView : WLResultsView { } -(CPSize)_minItemSize { return CGSizeMake(150,150); } -(CPSize)_maxItemSize { return CGSizeMake(150,150); } -(CPCollectionViewItem)_itemPrototype { return [[PhotoCell alloc] init]; } --(void)_resultsUpdated { - [_collectionView setContent:[]]; - [_collectionView setContent:_results]; -} - -(void)_search { var query = "/search/images?query="+encodeURIComponent(_searchString)+"&offset="+_offset; var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } --(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { - [self _setResults:eval(data)]; -} -- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error -{ - //alert("error: " + error); -} - --(void)connectionDidFinishLoading:(CPURLConnection)connection { - // finished -} - @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } /* -(void)setSelected:(BOOL)flag { if (!flag) return; //var view = [[imageView superview] superview]; //var bounds = [view bounds]; var mainWindow = [[CPApplication sharedApplication] mainWindow]; var point = [imageView convertRect:[imageView bounds] toView:[mainWindow contentView]]; var window = [[CPPanel alloc] initWithContentRect:CGRectMake(CGRectGetMinX(point),CGRectGetMinY(point),300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; var contentView = [window contentView]; var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(0,0,300,300) data:dict image:image]; [[window contentView] addSubview:aView]; [window orderFront:self]; */ } diff --git a/static/WLResultsView.j b/static/WLResultsView.j index 4f41784..611bb41 100644 --- a/static/WLResultsView.j +++ b/static/WLResultsView.j @@ -1,77 +1,92 @@ import <Foundation/CPObject.j> import "WLScrollView.j" @implementation WLResultsView : WLScrollView { CPArray _results; CPString _searchString; CPCollectionView _collectionView; int _offset; BOOL _recieved; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; _collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [_collectionView setDelegate:self]; [_collectionView setItemPrototype:[self _itemPrototype]]; [_collectionView setMinItemSize:[self _minItemSize]]; [_collectionView setMaxItemSize:[self _maxItemSize]]; [_collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:_collectionView]; [self setAutohidesScrollers:YES]; return self; } -(CPSize)_minItemSize { return CGSizeMake(150,150); } -(CPSize)_maxItemSize { return CGSizeMake(150,150); } -(CPCollectionViewItem)_itemPrototype { // implement in subclass } -(void)searchFor: (CPString)searchString { if ([_searchString caseInsensitiveCompare:searchString]==0) { // Don't re-search already search results. return; } [self _clearResults]; _searchString = searchString; _offset = 0; [self _search]; _offset = _offset + [self _offsetIncrement]; } -(int)_offsetIncrement { return 20; } -(void)_clearResults { _results = [[CPArray alloc] init]; } -(void)_setResults: (CPArray)anArray { [_results addObjectsFromArray:anArray]; [self _resultsUpdated]; _recieved = YES; } -(void)scrollerMovedToPosition: (float)scrollerPos { if (scrollerPos > 0.8 && _recieved != NO) { _recieved = NO; [self _search]; } } -(void)_resultsUpdated { - // override. + [_collectionView setContent:[]]; + [_collectionView setContent:_results]; } -(void)_search { // perform search, update with _setResults method. } + +-(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { + [self _setResults:eval(data)]; +} +- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error +{ + //alert("error: " + error); +} + +-(void)connectionDidFinishLoading:(CPURLConnection)connection { + // finished +} + +@end diff --git a/static/WLWebResultsView.j b/static/WLWebResultsView.j new file mode 100644 index 0000000..b3eb3a0 --- /dev/null +++ b/static/WLWebResultsView.j @@ -0,0 +1,90 @@ +import <Foundation/CPObject.j> +import "WLResultsView.j" +import "WLURLLabel.j" + +@implementation WLWebResultsView : WLResultsView { +} + +-(CPSize)_minItemSize { + //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); + return CGSizeMake(300,100); +} + +-(CPSize)_maxItemSize { + //return CGSizeMake(CGRectGetWidth([self bounds])-50,100); + return CGSizeMake(1500,100); +} + +-(CPCollectionViewItem)_itemPrototype { + return [[WebCell alloc] init]; +} + +-(void)_search { + var query = "/search/web?query="+encodeURIComponent(_searchString)+"&offset="+_offset; + var request = [CPURLRequest requestWithURL:query]; + var connection = [CPURLConnection connectionWithRequest:request delegate:self]; + [connection start]; +} +@end + +@implementation WebCell : CPCollectionViewItem { + CPDictionary dict; + CPView webView; +} + +-(void)setRepresentedObject: (CPDictionary)aDict { + dict = aDict; + + if (!webView) { + webView = [[CPView alloc] initWithFrame:CGRectMake(0,0,300,150)]; + [webView setBackgroundColor:[CPColor whiteColor]]; + [webView setAutoresizingMask: CPViewWidthSizable]; + + var bounds = [webView bounds]; + var frame = CGRectMake(0,0,CPRectGetMaxX(bounds),25); + var titleLabel = [self makeLabelWith:dict.title at:frame]; + [titleLabel setFont:[CPFont boldSystemFontOfSize:20.0]]; + [titleLabel setAlignment:CPLeftTextAlignment]; + [webView addSubview:titleLabel]; + + frame = CGRectMake(CPRectGetMaxX(bounds)-50,25,50,25); + var date = [self makeLabelWith:dict.date at:frame]; + [date setAlignment:CPRightTextAlignment]; + [webView addSubview:date]; + + frame = CGRectMake(0,25,CPRectGetWidth(bounds)-75,25); + var link = [self makeURLLabelWith:dict.url andUrl:dict.clickurl at:frame]; + [link setTextColor:[CPColor blueColor]]; + [webView addSubview:link]; + + frame = CGRectMake(0,50,CPRectGetWidth(bounds)-10,75); + var abstract = [self makeLabelWith:dict.abstract at:frame]; + [abstract setLineBreakMode:CPLineBreakByWordWrapping]; + [webView addSubview:abstract]; + + //[webView addSubiew:[self makeURLLabel]]; + //[webView addSubview:[self makeAbstractLabel]]; + + [self setView:webView]; + } + +} + +-(CPTextField)makeLabelWith: (CPString)aString at: (CPRect)aFrame { + var field = [[CPTextField alloc] initWithFrame:aFrame]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setStringValue:aString]; + [field setAutoresizingMask: CPViewWidthSizable]; + return field; +} + +-(CPTextField)makeURLLabelWith: (CPString)aString andUrl: (CPString)aURL at: (CPRect)aFrame { + var field = [[WLURLLabel alloc] initWithFrame:aFrame]; + [field setUrl:aURL]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setStringValue:aString]; + [field setAutoresizingMask: CPViewWidthSizable]; + return field; +} + +@end
lethain/mahou
1fe04b43ebf3bcbc3653fe2f1fc2e46090ddf2e3
Placeholder text doesn't exist as far as stringValue method is concerned, for better checking whether or not a textfield is empty.
diff --git a/static/Frameworks/AppKit/Resources/CPPopUpButton/CPPopUpButtonArrows.png b/static/Frameworks/AppKit/Resources/CPPopUpButton/CPPopUpButtonArrows.png new file mode 100644 index 0000000..018dd44 Binary files /dev/null and b/static/Frameworks/AppKit/Resources/CPPopUpButton/CPPopUpButtonArrows.png differ diff --git a/static/Frameworks/Info.plist b/static/Frameworks/Info.plist new file mode 100644 index 0000000..3a8260a --- /dev/null +++ b/static/Frameworks/Info.plist @@ -0,0 +1 @@ +<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version = "1.0"><dict><key>CPBundleIdentifier</key><string>com.280n.Foundation</string><key>CPBundleInfoDictionaryVersion</key><string>6.0</string><key>CPBundleName</key><string>Foundation</string><key>CPBundlePackageType</key><string>FMWK</string><key>CPBundleExecutable</key><string>Foundation.sj</string><key>CPBundleReplacedFiles</key><array><string>CPArray.j</string><string>CPBundle.j</string><string>CPCoder.j</string><string>CPData.j</string><string>CPDictionary.j</string><string>CPEnumerator.j</string><string>CPException.j</string><string>CPIndexSet.j</string><string>CPInvocation.j</string><string>CPJSONPConnection.j</string><string>CPKeyedArchiver.j</string><string>CPKeyedUnarchiver.j</string><string>CPKeyValueCoding.j</string><string>CPLog.j</string><string>CPNotification.j</string><string>CPNotificationCenter.j</string><string>CPNull.j</string><string>CPNumber.j</string><string>CPObject.j</string><string>CPObjJRuntime.j</string><string>CPPropertyListSerialization.j</string><string>CPRange.j</string><string>CPRunLoop.j</string><string>CPSortDescriptor.j</string><string>CPString.j</string><string>CPUndoManager.j</string><string>CPURLConnection.j</string><string>CPURLRequest.j</string><string>CPURLResponse.j</string><string>CPUserSessionManager.j</string><string>CPValue.j</string><string>Foundation.j</string></array></dict></plist> \ No newline at end of file diff --git a/static/WLTextField.j b/static/WLTextField.j index 88abffe..2a858c1 100644 --- a/static/WLTextField.j +++ b/static/WLTextField.j @@ -1,32 +1,40 @@ import <Foundation/CPObject.j> import <AppKit/CPTextField.j> @implementation WLTextField : CPTextField { CPString placeholderString; } +-(CPString) stringValue { + var s = [super stringValue]; + if ([s caseInsensitiveCompare:placeholderString]==0) { + return @""; + } + return s; +} + -(BOOL)becomeFirstResponder { if ([[self stringValue] caseInsensitiveCompare:[self placeholderString]]==0) { [self setStringValue:@""]; } return [super becomeFirstResponder]; } -(BOOL)resignFirstResponder { if ([[self stringValue] caseInsensitiveCompare:@""]==0) { [self setStringValue:[self placeholderString]]; } return [super resignFirstResponder]; } -(void)setPlaceholderString: (CPString)aString { placeholderString = aString; } -(CPString)placeholderString { return placeholderString; } @end
lethain/mahou
821a52cbb48cbfccf82cbb94f40c2a976b8bd5f8
Fleshing out new Imageresults view.
diff --git a/static/AppController.j b/static/AppController.j index 81533d5..26372f7 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,125 +1,126 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; CPView webView; CPView imageView; CPView newsView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; [theWindow orderFront:self]; [CPMenu setMenuBarVisible:YES]; } -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; [tabView setTabViewType:CPTopTabsBezelBorder]; //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; webView = [[WLResultsView alloc] initWithFrame:CPRectMakeZero()]; imageView = [[WLResultsView alloc] initWithFrame:CPRectMakeZero()]; newsView = [[WLResultsView alloc] initWithFrame:CPRectMakeZero()]; [webSearchTabItem setLabel:@"Web"]; [imageSearchTabItem setLabel:@"Image"]; [newsSearchTabItem setLabel:@"News"]; [webSearchTabItem setView:webView]; [imageSearchTabItem setView:imageView]; [newsSearchTabItem setView:newsView]; [tabView addTabViewItem:webSearchTabItem]; [tabView addTabViewItem:imageSearchTabItem]; [tabView addTabViewItem:newsSearchTabItem]; + // Select Image tab. + [tabView selectTabViewItemAtIndex:1]; - [tabView selectTabViewItemAtIndex:0]; [contentView addSubview:tabView]; } @end diff --git a/static/OldWLImageResultsView.j b/static/OldWLImageResultsView.j new file mode 100644 index 0000000..22828e3 --- /dev/null +++ b/static/OldWLImageResultsView.j @@ -0,0 +1,118 @@ +import <Foundation/CPObject.j> +import "AppController.j" +import "WLImageDisplayView.j" + +@implementation WLImageResultsView : CPScrollView { + CPCollectionView collectionView; + CPArray images; + AppController appController; + BOOL recievedAdditional; +} + +-(id)initWithFrame:aFrame { + self = [super initWithFrame:aFrame]; + var photoItem = [[PhotoCell alloc] init]; + collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; + [collectionView setDelegate:self]; + [collectionView setItemPrototype:photoItem]; + [collectionView setMinItemSize:CGSizeMake(150, 150)]; + [collectionView setMaxItemSize:CGSizeMake(150, 150)]; + [collectionView setAutoresizingMask: CPViewWidthSizable]; + [self setDocumentView:collectionView]; + [self setAutohidesScrollers:YES]; + [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; + return self; +} + +-(void)setAppController: (AppController)appCont { + appController = appCont; +} +-(AppController)appController { + return appController; +} + +-(void)scrollWheel:(CPEvent)anEvent { + [self considerNotifying]; + [super scrollWheel:anEvent]; +} + +-(void)considerNotifying { + var scroller = [self verticalScroller]; + var position = [scroller floatValue]; + if (position > .8 && recievedAdditional) { + [[self appController] retrieveAdditional]; + recievedAdditional = NO; + + } +} + +-(void)clearResults { + images = [[CPArray alloc] init]; +} + +-(void)setImages: (CPArray)anArray { + var recievedAdditional = YES; + var newResults = eval(anArray); + [images addObjectsFromArray:newResults]; + [collectionView setContent:[]]; + [collectionView setContent:images]; +} +-(CPArray)images { + return images; +} + +-(void)mouseDown(CPEvent)anEvent { + alert("mouse down!"); +} + +@end + +@implementation PhotoCell : CPCollectionViewItem { + CPImage image; + CPImageView imageView; + CPDictionary dict; +} + +-(void)setRepresentedObject: (CPDictionary)aDict { + dict = aDict; + if (!imageView) { + imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; + [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; + [imageView setImageScaling: CPScaleProportionally]; + [imageView setHasShadow:YES]; + [self setView:imageView]; + } + + if (image) + [image setDelegate:nil]; + + image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; + [image setDelegate:self]; + if([image loadStatus] == CPImageLoadStatusCompleted) + [imageView setImage: image]; + else + [imageView setImage: nil]; +} + +- (void)imageDidLoad:(CPImage)anImage { + [imageView setImage: anImage]; +} + +-(void)setSelected:(BOOL)flag { + if (!flag) return; + + //var view = [[imageView superview] superview]; + //var bounds = [view bounds]; + var mainWindow = [[CPApplication sharedApplication] mainWindow]; + var point = [imageView convertRect:[imageView bounds] toView:[mainWindow contentView]]; + + + var window = [[CPPanel alloc] initWithContentRect:CGRectMake(CGRectGetMinX(point),CGRectGetMinY(point),300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; + var contentView = [window contentView]; + + var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(0,0,300,300) data:dict image:image]; + [[window contentView] addSubview:aView]; + [window orderFront:self]; +} + +@end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index 22828e3..7432ecb 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,118 +1,86 @@ import <Foundation/CPObject.j> -import "AppController.j" -import "WLImageDisplayView.j" - -@implementation WLImageResultsView : CPScrollView { - CPCollectionView collectionView; - CPArray images; - AppController appController; - BOOL recievedAdditional; -} +import "WLResultsView.j" --(id)initWithFrame:aFrame { - self = [super initWithFrame:aFrame]; - var photoItem = [[PhotoCell alloc] init]; - collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; - [collectionView setDelegate:self]; - [collectionView setItemPrototype:photoItem]; - [collectionView setMinItemSize:CGSizeMake(150, 150)]; - [collectionView setMaxItemSize:CGSizeMake(150, 150)]; - [collectionView setAutoresizingMask: CPViewWidthSizable]; - [self setDocumentView:collectionView]; - [self setAutohidesScrollers:YES]; - [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; - return self; +@implementation WLImageResultsView : WLResultsView { + } --(void)setAppController: (AppController)appCont { - appController = appCont; -} --(AppController)appController { - return appController; +-(CPSize)_minItemSize { + return CGSizeMake(150,150); } --(void)scrollWheel:(CPEvent)anEvent { - [self considerNotifying]; - [super scrollWheel:anEvent]; +-(CPSize)_maxItemSize { + return CGSizeMake(150,150); } --(void)considerNotifying { - var scroller = [self verticalScroller]; - var position = [scroller floatValue]; - if (position > .8 && recievedAdditional) { - [[self appController] retrieveAdditional]; - recievedAdditional = NO; - - } +-(CPCollectionViewItem)_itemPrototype { + return [[PhotoCell alloc] init]; } --(void)clearResults { - images = [[CPArray alloc] init]; +-(void)_search { + var query = "/search/images?query="+encodeURIComponent(_searchString)+"&offset="+encodeURIComponent(_offset); + var request = [CPURLRequest requestWithURL:query]; + var connection = [CPURLConnection connectionWithRequest:request delegate:self]; + [connection start]; } --(void)setImages: (CPArray)anArray { - var recievedAdditional = YES; - var newResults = eval(anArray); - [images addObjectsFromArray:newResults]; - [collectionView setContent:[]]; - [collectionView setContent:images]; -} --(CPArray)images { - return images; +-(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { + [imageResultsView setImages:eval(data)]; } --(void)mouseDown(CPEvent)anEvent { - alert("mouse down!"); -} @end + + @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } +/* -(void)setSelected:(BOOL)flag { if (!flag) return; //var view = [[imageView superview] superview]; //var bounds = [view bounds]; var mainWindow = [[CPApplication sharedApplication] mainWindow]; var point = [imageView convertRect:[imageView bounds] toView:[mainWindow contentView]]; var window = [[CPPanel alloc] initWithContentRect:CGRectMake(CGRectGetMinX(point),CGRectGetMinY(point),300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; var contentView = [window contentView]; var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(0,0,300,300) data:dict image:image]; [[window contentView] addSubview:aView]; [window orderFront:self]; +*/ } -@end + diff --git a/static/WLResultsView.j b/static/WLResultsView.j index db1a569..7b37632 100644 --- a/static/WLResultsView.j +++ b/static/WLResultsView.j @@ -1,67 +1,72 @@ import <Foundation/CPObject.j> import "WLScrollView.j" @implementation WLResultsView : WLScrollView { CPArray _results; CPString _searchString; CPCollectionView _collectionView; - int offset; + int _offset; BOOL _recieved; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; _collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [_collectionView setDelegate:self]; [_collectionView setItemPrototype:[self _itemPrototype]]; [_collectionView setMinItemSize:[self _minItemSize]]; [_collectionView setMaxItemSize:[self _maxItemSize]]; [_collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:_collectionView]; [self setAutohidesScrollers:YES]; return self; } -(CPSize)_minItemSize { return CGSizeMake(150,150); } -(CPSize)_maxItemSize { return CGSizeMake(150,150); } -(CPCollectionViewItem)_itemPrototype { // implement in subclass } -(void)searchFor: (CPString)searchString { [self _clearResults]; _searchString = searchString; - offset = 0; + _offset = 0; [self _search]; + _offset = _offset + [self _offsetIncrement]; +} + +-(int)_offsetIncrement { + return 20; } -(void)_clearResults { _results = [[CPArray alloc] init]; } -(void)_setResults: (CPArray)anArray { [_results addObjectsFromArray:anArray]; [self _resultsUpdated]; _recieved = YES; } -(void)scrollerMovedToPosition: (float)scrollerPos { if (scrollerPos > 0.8 && _recieved != NO) { _recieved = NO; [self _search]; } } -(void)_resultsUpdated { // override. } -(void)_search { // perform search, update with _setResults method. }
lethain/mahou
5acebb85f15e0af8e8c9e683ff6bd9814e94dd60
Initial implementation of results view.
diff --git a/static/AppController.j b/static/AppController.j index 5eb5255..81533d5 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,96 +1,125 @@ import <Foundation/CPObject.j> import "WLTextField.j" +import "WLResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton searchButton; CPTabView tabView; CPTabViewItem webSearchTabItem; CPTabViewItem imageSearchTabItem; CPTabViewItem newsSearchTabItem; + CPView webView; + CPView imageView; + CPView newsView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; var contentView = [theWindow contentView]; [self setupSearchFieldAndButton:contentView]; [self setupTabView:contentView]; [theWindow orderFront:self]; [CPMenu setMenuBarVisible:YES]; } -(void)setupSearchFieldAndButton: (CPView)contentView { var bounds = [contentView bounds]; var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, CGRectGetMinY(bounds)+15, CGRectGetWidth(bounds)/1.5, 70); var view = [[CPView alloc] initWithFrame:searchFrame]; //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; bounds = [view bounds]; // Create the search field. var frame = CGRectMake(CGRectGetMinX(bounds)+10, CGRectGetMinY(bounds)+10, CGRectGetWidth(bounds)-100, CGRectGetMaxY(bounds)-20); searchField = [[WLTextField alloc] initWithFrame:frame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBackgroundColor: [CPColor whiteColor]]; [view addSubview:searchField]; var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, CGRectGetMinY(bounds)+9, CGRectGetWidth(bounds)-98, CGRectGetMaxY(bounds)-18); var borderView = [[CPView alloc] initWithFrame:borderFrame]; [borderView setBackgroundColor:[CPColor lightGrayColor]]; [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, CGRectGetMinY(bounds)+3, 64,64); searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; [searchButton setImage:image]; [searchButton setAlternateImage:altImage]; [searchButton setImagePosition:CPImageOnly]; [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchButton setBordered:NO]; [searchButton setTitle:"search"]; [searchButton setTarget:self]; [searchButton setAction:@selector(search:)]; [view addSubview:searchButton]; // Add everything to main content view [contentView addSubview:view]; } -(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; var frame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); tabView = [[CPTabView alloc] initWithFrame:frame]; + [tabView setTabViewType:CPTopTabsBezelBorder]; + //[tabView layoutSubviews]; [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; + + webSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"web"]; + imageSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"image"]; + newsSearchTabItem = [[CPTabViewItem alloc] initWithIdentifier:@"news"]; + + webView = [[WLResultsView alloc] initWithFrame:CPRectMakeZero()]; + imageView = [[WLResultsView alloc] initWithFrame:CPRectMakeZero()]; + newsView = [[WLResultsView alloc] initWithFrame:CPRectMakeZero()]; + + [webSearchTabItem setLabel:@"Web"]; + [imageSearchTabItem setLabel:@"Image"]; + [newsSearchTabItem setLabel:@"News"]; + + [webSearchTabItem setView:webView]; + [imageSearchTabItem setView:imageView]; + [newsSearchTabItem setView:newsView]; + + [tabView addTabViewItem:webSearchTabItem]; + [tabView addTabViewItem:imageSearchTabItem]; + [tabView addTabViewItem:newsSearchTabItem]; + + + [tabView selectTabViewItemAtIndex:0]; [contentView addSubview:tabView]; } @end diff --git a/static/WLResultsView.j b/static/WLResultsView.j new file mode 100644 index 0000000..db1a569 --- /dev/null +++ b/static/WLResultsView.j @@ -0,0 +1,67 @@ +import <Foundation/CPObject.j> +import "WLScrollView.j" + +@implementation WLResultsView : WLScrollView { + CPArray _results; + CPString _searchString; + CPCollectionView _collectionView; + int offset; + BOOL _recieved; +} + +-(id)initWithFrame:aFrame { + self = [super initWithFrame:aFrame]; + _collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; + [_collectionView setDelegate:self]; + [_collectionView setItemPrototype:[self _itemPrototype]]; + [_collectionView setMinItemSize:[self _minItemSize]]; + [_collectionView setMaxItemSize:[self _maxItemSize]]; + [_collectionView setAutoresizingMask: CPViewWidthSizable]; + [self setDocumentView:_collectionView]; + [self setAutohidesScrollers:YES]; + return self; +} + +-(CPSize)_minItemSize { + return CGSizeMake(150,150); +} + +-(CPSize)_maxItemSize { + return CGSizeMake(150,150); +} + +-(CPCollectionViewItem)_itemPrototype { + // implement in subclass +} + +-(void)searchFor: (CPString)searchString { + [self _clearResults]; + _searchString = searchString; + offset = 0; + [self _search]; +} + +-(void)_clearResults { + _results = [[CPArray alloc] init]; +} + +-(void)_setResults: (CPArray)anArray { + [_results addObjectsFromArray:anArray]; + [self _resultsUpdated]; + _recieved = YES; +} + +-(void)scrollerMovedToPosition: (float)scrollerPos { + if (scrollerPos > 0.8 && _recieved != NO) { + _recieved = NO; + [self _search]; + } +} + +-(void)_resultsUpdated { + // override. +} + +-(void)_search { + // perform search, update with _setResults method. +} diff --git a/static/WLScrollView.j b/static/WLScrollView.j new file mode 100644 index 0000000..fed36a8 --- /dev/null +++ b/static/WLScrollView.j @@ -0,0 +1,17 @@ + +import <Foundation/CPObject.j> + +@implementation WLScrollView : CPScrollView {} + +-(void)scrollWheel:(CPEvent)anEvent { + var scroller = [self verticalScroller]; + var position = [scroller floatValue]; + [self scrollerMovedToPosition:position]; + [super scrollWheel:anEvent]; +} + +-(void)scrollerMovedToPosition: (float)scrollerPos { + // Should be overridden by subclasses. +} + +@end
lethain/mahou
c7381eef110fbed0f3c9c55fed9801aa2222f9c4
Revamping to new UI. Rough positional setup.
diff --git a/static/AppController.j b/static/AppController.j index 65f76a5..5eb5255 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,131 +1,96 @@ import <Foundation/CPObject.j> import "WLTextField.j" -import "WLURLLabel.j" -import "WLImageResultsView.j" @implementation AppController : CPObject { WLTextField searchField; - CPButton button; - WLImageResultsView imageResultsView; - CPArray results; - int offset; - CPString search; + CPButton searchButton; + CPTabView tabView; + CPTabViewItem webSearchTabItem; + CPTabViewItem imageSearchTabItem; + CPTabViewItem newsSearchTabItem; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { + var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask]; + var contentView = [theWindow contentView]; - var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], - contentView = [theWindow contentView]; - [contentView setBackgroundColor: [CPColor grayColor]]; - - var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); - searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; - [searchField setPlaceholderString:@"type your search here"]; - [searchField setStringValue:[searchField placeholderString]]; - [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; - [searchField setEditable:YES]; - [searchField setSelectable:YES]; - [searchField setBordered:YES]; - [searchField setBezeled:YES]; - [searchField setBezelStyle:CPTextFieldRoundedBezel]; - [searchField setBackgroundColor: [CPColor whiteColor]]; - [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; - [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; - - - [contentView addSubview:searchField]; - - var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; - - var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, - CGRectGetMinY([searchField frame])-16, - 64,64); - button = [[CPButton alloc] initWithFrame:buttonFrame]; - [button setImage:image]; - [button setAlternateImage:altImage]; - [button setImagePosition:CPImageOnly]; - [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; - [button setBordered:NO]; - [button setTitle:"search"]; - [button setTarget:self]; - [button setAction:@selector(search:)]; - [contentView addSubview:button]; - - [self setupPhotosCollectionView:contentView]; - [self setupAttributionLabel:contentView]; - - - [theWindow orderFront:self]; - - // Uncomment the following line to turn on the standard menu bar. - //[CPMenu setMenuBarVisible:YES]; -} - -- (void)search:(id)sender { - offset = 0; - search = [searchField stringValue]; - [imageResultsView clearResults]; - [self searchYahooImagesFor:search withOffset:offset]; -} - --(void)retrieveAdditional { - offset += 20; - [self searchYahooImagesFor:search withOffset:offset]; -} - --(void)searchYahooImagesFor: (CPString)aString withOffset: (int)aNumber { - var query = "/search/images?query="+encodeURIComponent(aString)+"&offset="+encodeURIComponent(aNumber); - var request = [CPURLRequest requestWithURL:query]; - var connection = [CPURLConnection connectionWithRequest:request delegate:self]; - [connection start]; + [self setupSearchFieldAndButton:contentView]; + [self setupTabView:contentView]; + [theWindow orderFront:self]; + [CPMenu setMenuBarVisible:YES]; } +-(void)setupSearchFieldAndButton: (CPView)contentView { + - --(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { - [imageResultsView setImages:data]; -} - -- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error -{ - //alert("error: " + error); -} - --(void)connectionDidFinishLoading:(CPURLConnection)connection {} - -/* --(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { - alert("response: " + response); -} -*/ - --(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; - var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); - var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; - - [field setStringValue:@"Mahou by Will Larson (http://lethain.com/)"]; - [field setUrl:@"http://lethain.com/"]; - [field setFont:[CPFont boldSystemFontOfSize:12.0]]; - [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; - [field setTextColor:[CPColor whiteColor]]; - [field sizeToFit]; - [contentView addSubview:field]; + var searchFrame = CGRectMake(CGRectGetWidth(bounds)/6, + CGRectGetMinY(bounds)+15, + CGRectGetWidth(bounds)/1.5, + 70); + var view = [[CPView alloc] initWithFrame:searchFrame]; + //[view setBackgroundColor:[CPColor shadowColor]]; //lightGray + [view setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; + + + bounds = [view bounds]; + // Create the search field. + var frame = CGRectMake(CGRectGetMinX(bounds)+10, + CGRectGetMinY(bounds)+10, + CGRectGetWidth(bounds)-100, + CGRectGetMaxY(bounds)-20); + searchField = [[WLTextField alloc] initWithFrame:frame]; + [searchField setPlaceholderString:@"type your search here"]; + [searchField setStringValue:[searchField placeholderString]]; + [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; + [searchField setEditable:YES]; + [searchField setSelectable:YES]; + [searchField setBordered:YES]; + [searchField setBackgroundColor: [CPColor whiteColor]]; + [view addSubview:searchField]; + + + var borderFrame = CGRectMake(CGRectGetMinX(bounds)+9, + CGRectGetMinY(bounds)+9, + CGRectGetWidth(bounds)-98, + CGRectGetMaxY(bounds)-18); + var borderView = [[CPView alloc] initWithFrame:borderFrame]; + [borderView setBackgroundColor:[CPColor lightGrayColor]]; + [view addSubview:borderView positioned:CPWindowBelow relativeTo:searchField]; + + + var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; + + var buttonFrame = CGRectMake(CGRectGetMaxX(bounds)-72, + CGRectGetMinY(bounds)+3, + 64,64); + searchButton = [[CPButton alloc] initWithFrame:buttonFrame]; + [searchButton setImage:image]; + [searchButton setAlternateImage:altImage]; + [searchButton setImagePosition:CPImageOnly]; + [searchButton setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; + [searchButton setBordered:NO]; + [searchButton setTitle:"search"]; + [searchButton setTarget:self]; + [searchButton setAction:@selector(search:)]; + [view addSubview:searchButton]; + + // Add everything to main content view + [contentView addSubview:view]; } --(void)setupPhotosCollectionView: (CPView)contentView { +-(void)setupTabView: (CPView)contentView { var bounds = [contentView bounds]; - var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, - CGRectGetMinY(bounds)+100, - CGRectGetWidth(bounds)-150, - CGRectGetHeight(bounds)-200); - imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; - [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; - [imageResultsView setAppController:self]; - [contentView addSubview:imageResultsView]; + var frame = CGRectMake(CGRectGetMinX(bounds)+75, + CGRectGetMinY(bounds)+100, + CGRectGetWidth(bounds)-150, + CGRectGetHeight(bounds)-200); + tabView = [[CPTabView alloc] initWithFrame:frame]; + [tabView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; + [contentView addSubview:tabView]; } @end diff --git a/static/OldAppController.js b/static/OldAppController.js new file mode 100644 index 0000000..65f76a5 --- /dev/null +++ b/static/OldAppController.js @@ -0,0 +1,131 @@ + +import <Foundation/CPObject.j> +import "WLTextField.j" +import "WLURLLabel.j" +import "WLImageResultsView.j" + +@implementation AppController : CPObject +{ + WLTextField searchField; + CPButton button; + WLImageResultsView imageResultsView; + CPArray results; + int offset; + CPString search; +} + +- (void)applicationDidFinishLaunching:(CPNotification)aNotification +{ + + var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], + contentView = [theWindow contentView]; + [contentView setBackgroundColor: [CPColor grayColor]]; + + var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); + searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; + [searchField setPlaceholderString:@"type your search here"]; + [searchField setStringValue:[searchField placeholderString]]; + [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; + [searchField setEditable:YES]; + [searchField setSelectable:YES]; + [searchField setBordered:YES]; + [searchField setBezeled:YES]; + [searchField setBezelStyle:CPTextFieldRoundedBezel]; + [searchField setBackgroundColor: [CPColor whiteColor]]; + [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; + [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; + + + [contentView addSubview:searchField]; + + var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; + + var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, + CGRectGetMinY([searchField frame])-16, + 64,64); + button = [[CPButton alloc] initWithFrame:buttonFrame]; + [button setImage:image]; + [button setAlternateImage:altImage]; + [button setImagePosition:CPImageOnly]; + [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; + [button setBordered:NO]; + [button setTitle:"search"]; + [button setTarget:self]; + [button setAction:@selector(search:)]; + [contentView addSubview:button]; + + [self setupPhotosCollectionView:contentView]; + [self setupAttributionLabel:contentView]; + + + [theWindow orderFront:self]; + + // Uncomment the following line to turn on the standard menu bar. + //[CPMenu setMenuBarVisible:YES]; +} + +- (void)search:(id)sender { + offset = 0; + search = [searchField stringValue]; + [imageResultsView clearResults]; + [self searchYahooImagesFor:search withOffset:offset]; +} + +-(void)retrieveAdditional { + offset += 20; + [self searchYahooImagesFor:search withOffset:offset]; +} + +-(void)searchYahooImagesFor: (CPString)aString withOffset: (int)aNumber { + var query = "/search/images?query="+encodeURIComponent(aString)+"&offset="+encodeURIComponent(aNumber); + var request = [CPURLRequest requestWithURL:query]; + var connection = [CPURLConnection connectionWithRequest:request delegate:self]; + [connection start]; +} + + + +-(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { + [imageResultsView setImages:data]; +} + +- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error +{ + //alert("error: " + error); +} + +-(void)connectionDidFinishLoading:(CPURLConnection)connection {} + +/* +-(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { + alert("response: " + response); +} +*/ + +-(void)setupAttributionLabel: (CPView)contentView { + var bounds = [contentView bounds]; + var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); + var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; + + [field setStringValue:@"Mahou by Will Larson (http://lethain.com/)"]; + [field setUrl:@"http://lethain.com/"]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; + [field setTextColor:[CPColor whiteColor]]; + [field sizeToFit]; + [contentView addSubview:field]; +} + +-(void)setupPhotosCollectionView: (CPView)contentView { + var bounds = [contentView bounds]; + var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, + CGRectGetMinY(bounds)+100, + CGRectGetWidth(bounds)-150, + CGRectGetHeight(bounds)-200); + imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; + [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; + [imageResultsView setAppController:self]; + [contentView addSubview:imageResultsView]; +} + +@end
lethain/mahou
c93475ec3e728942e434fa784fc019e14229f071
Commented out error message.
diff --git a/static/AppController.j b/static/AppController.j index 0d7642a..65f76a5 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,131 +1,131 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" import "WLImageResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; WLImageResultsView imageResultsView; CPArray results; int offset; CPString search; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(search:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } - (void)search:(id)sender { offset = 0; search = [searchField stringValue]; [imageResultsView clearResults]; [self searchYahooImagesFor:search withOffset:offset]; } -(void)retrieveAdditional { offset += 20; [self searchYahooImagesFor:search withOffset:offset]; } -(void)searchYahooImagesFor: (CPString)aString withOffset: (int)aNumber { var query = "/search/images?query="+encodeURIComponent(aString)+"&offset="+encodeURIComponent(aNumber); var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { [imageResultsView setImages:data]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { - alert("error: " + error); + //alert("error: " + error); } -(void)connectionDidFinishLoading:(CPURLConnection)connection {} /* -(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { alert("response: " + response); } */ -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; [field setStringValue:@"Mahou by Will Larson (http://lethain.com/)"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; [imageResultsView setAppController:self]; [contentView addSubview:imageResultsView]; } @end
lethain/mahou
d3b65d6c05b4315d6a43932922d987a9ec385f37
Changed path for simplejson for GAE.
diff --git a/main.py b/main.py index 0770dea..95fb965 100755 --- a/main.py +++ b/main.py @@ -1,57 +1,57 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. __author__ = "Vik Singh ([email protected])" import logging import wsgiref.handlers from google.appengine.ext import webapp from yos.crawl.rest import download from yos.util import console from yos.boss import ysearch from yos.yql import db -import simplejson +from django.utils import simplejson class ImageSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) offset = int(console.strfix(self.request.get("offset"))) data = ysearch.search(query,vertical="images",count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) class RootHandler(webapp.RequestHandler): def get(self): self.redirect(ROOT_REDIRECT) def main(): logging.getLogger().setLevel(logging.DEBUG) application = webapp.WSGIApplication([('/', RootHandler), ('/search/images', ImageSearchHandler), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
lethain/mahou
af68483a5ae6d6bfa84e36b3e6e6b4e629b2941d
Now displaying images in the correct location. Woohoo.
diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index eb1ae3c..22828e3 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,112 +1,118 @@ import <Foundation/CPObject.j> import "AppController.j" import "WLImageDisplayView.j" @implementation WLImageResultsView : CPScrollView { CPCollectionView collectionView; CPArray images; AppController appController; BOOL recievedAdditional; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; var photoItem = [[PhotoCell alloc] init]; collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [collectionView setDelegate:self]; [collectionView setItemPrototype:photoItem]; [collectionView setMinItemSize:CGSizeMake(150, 150)]; [collectionView setMaxItemSize:CGSizeMake(150, 150)]; [collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:collectionView]; [self setAutohidesScrollers:YES]; [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; return self; } -(void)setAppController: (AppController)appCont { appController = appCont; } -(AppController)appController { return appController; } -(void)scrollWheel:(CPEvent)anEvent { [self considerNotifying]; [super scrollWheel:anEvent]; } -(void)considerNotifying { var scroller = [self verticalScroller]; var position = [scroller floatValue]; if (position > .8 && recievedAdditional) { [[self appController] retrieveAdditional]; recievedAdditional = NO; } } -(void)clearResults { images = [[CPArray alloc] init]; } -(void)setImages: (CPArray)anArray { var recievedAdditional = YES; var newResults = eval(anArray); [images addObjectsFromArray:newResults]; [collectionView setContent:[]]; [collectionView setContent:images]; } -(CPArray)images { return images; } -(void)mouseDown(CPEvent)anEvent { alert("mouse down!"); } @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } -(void)setSelected:(BOOL)flag { if (!flag) return; - var cv = [self collectionView]; - var window = [[CPPanel alloc] initWithContentRect:CGRectMake(100,100,300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; + + //var view = [[imageView superview] superview]; + //var bounds = [view bounds]; + var mainWindow = [[CPApplication sharedApplication] mainWindow]; + var point = [imageView convertRect:[imageView bounds] toView:[mainWindow contentView]]; + + + var window = [[CPPanel alloc] initWithContentRect:CGRectMake(CGRectGetMinX(point),CGRectGetMinY(point),300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; var contentView = [window contentView]; var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(0,0,300,300) data:dict image:image]; [[window contentView] addSubview:aView]; [window orderFront:self]; } @end
lethain/mahou
603e8c7263251eca7058970d6977f0699406375a
Now displaying useful data.
diff --git a/static/WLImageDisplayView.j b/static/WLImageDisplayView.j index cc941c1..2fda53d 100644 --- a/static/WLImageDisplayView.j +++ b/static/WLImageDisplayView.j @@ -1,62 +1,73 @@ import <Foundation/CPObject.j> import "WLURLLabel.j" @implementation WLImageDisplayView : CPView { CPDictionary data; CPImageView imageView; } -(id)initWithFrame:aFrame data: (CPDictionary)aDict image: (CPImage)anImage { self = [super initWithFrame:aFrame]; data = aDict; var bounds = [self bounds]; imageView = [[CPImageView alloc] initWithFrame:CGRectMake(25,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [imageView setImage:anImage]; // height, width, format // abstract [self addSubview:[self makeTitleLabel]]; [self addSubview:imageView]; [self addSubview:[self makeDimensionsLabel]]; + [self addSubview:[self makeAbstractLabel]]; return self; } -(CPTextField)makeAbstractLabel { - var fieldFrame = CGRectMake(0,190,300,100); + var fieldFrame = CGRectMake(0,190,285,70); + var scrollView = [[CPScrollView alloc] initWithFrame:fieldFrame]; + //[scrollView setAutohidesScrollers:YES]; + [scrollView setHasHorizontalScroller:NO]; + + fieldFrame = CGRectMake(0,0,280,150); + var field = [[CPTextField alloc] initWithFrame:fieldFrame]; - alert(dict.abstract); - [field setStringValue:dict.abstract]; + [field setLineBreakMode:CPLineBreakByWordWrapping]; + [field setStringValue:data.abstract]; [field setTextColor:[CPColor grayColor]]; - return field; + //[field sizeToFit]; + + [scrollView setDocumentView:field]; + + return scrollView; } -(WLURLLabel)makeTitleLabel { var bounds = [self bounds]; var fieldFrame = CGRectMake(0,150,300,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; if (data.title) [field setStringValue:data.title]; else [field setStringValue:"untitled image"]; [field setUrl:data.clickurl]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setTextColor:[CPColor whiteColor]]; return field; } -(CPTextField)makeDimensionsLabel { var fieldFrame = CGRectMake(0,170,300,30); var string = "dimensions:"+data.width+" by "+data.height+"; format: " + data.format; var field = [[CPTextField alloc] initWithFrame:fieldFrame]; [field setStringValue:string]; [field setTextColor:[CPColor grayColor]]; return field; } @end
lethain/mahou
ae50b656722065116352f03db9f6fbe0dd09e246
Close to perfection, just need to display abstracts.
diff --git a/static/AppController.j b/static/AppController.j index c3cb90a..0d7642a 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,131 +1,131 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" import "WLImageResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; WLImageResultsView imageResultsView; CPArray results; int offset; CPString search; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(search:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } - (void)search:(id)sender { offset = 0; search = [searchField stringValue]; [imageResultsView clearResults]; [self searchYahooImagesFor:search withOffset:offset]; } -(void)retrieveAdditional { offset += 20; [self searchYahooImagesFor:search withOffset:offset]; } -(void)searchYahooImagesFor: (CPString)aString withOffset: (int)aNumber { var query = "/search/images?query="+encodeURIComponent(aString)+"&offset="+encodeURIComponent(aNumber); var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { [imageResultsView setImages:data]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { alert("error: " + error); } -(void)connectionDidFinishLoading:(CPURLConnection)connection {} /* -(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { alert("response: " + response); } */ -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; - [field setStringValue:@"Mahou by Will Larson"]; + [field setStringValue:@"Mahou by Will Larson (http://lethain.com/)"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; [imageResultsView setAppController:self]; [contentView addSubview:imageResultsView]; } @end diff --git a/static/WLImageDisplayView.j b/static/WLImageDisplayView.j index eea4975..cc941c1 100644 --- a/static/WLImageDisplayView.j +++ b/static/WLImageDisplayView.j @@ -1,44 +1,62 @@ import <Foundation/CPObject.j> import "WLURLLabel.j" @implementation WLImageDisplayView : CPView { CPDictionary data; + CPImageView imageView; } -(id)initWithFrame:aFrame data: (CPDictionary)aDict image: (CPImage)anImage { self = [super initWithFrame:aFrame]; data = aDict; - - var imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; + var bounds = [self bounds]; + imageView = [[CPImageView alloc] initWithFrame:CGRectMake(25,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [imageView setImage:anImage]; // height, width, format - // title, clickurl // abstract - - - - [self addSubview:imageView]; [self addSubview:[self makeTitleLabel]]; + [self addSubview:imageView]; + [self addSubview:[self makeDimensionsLabel]]; return self; } +-(CPTextField)makeAbstractLabel { + var fieldFrame = CGRectMake(0,190,300,100); + var field = [[CPTextField alloc] initWithFrame:fieldFrame]; + alert(dict.abstract); + [field setStringValue:dict.abstract]; + [field setTextColor:[CPColor grayColor]]; + return field; +} + -(WLURLLabel)makeTitleLabel { - var fieldFrame = CGRectMake(20,180,200,30); + var bounds = [self bounds]; + var fieldFrame = CGRectMake(0,150,300,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; - alert(data.title); - [field setStringValue:data.title]; + if (data.title) + [field setStringValue:data.title]; + else + [field setStringValue:"untitled image"]; + [field setUrl:data.clickurl]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; - [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; - //[field sizeToFit]; + return field; +} + +-(CPTextField)makeDimensionsLabel { + var fieldFrame = CGRectMake(0,170,300,30); + var string = "dimensions:"+data.width+" by "+data.height+"; format: " + data.format; + var field = [[CPTextField alloc] initWithFrame:fieldFrame]; + [field setStringValue:string]; + [field setTextColor:[CPColor grayColor]]; return field; } @end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index ee8ed86..eb1ae3c 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,112 +1,112 @@ import <Foundation/CPObject.j> import "AppController.j" import "WLImageDisplayView.j" @implementation WLImageResultsView : CPScrollView { CPCollectionView collectionView; CPArray images; AppController appController; BOOL recievedAdditional; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; var photoItem = [[PhotoCell alloc] init]; collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [collectionView setDelegate:self]; [collectionView setItemPrototype:photoItem]; [collectionView setMinItemSize:CGSizeMake(150, 150)]; [collectionView setMaxItemSize:CGSizeMake(150, 150)]; [collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:collectionView]; [self setAutohidesScrollers:YES]; [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; return self; } -(void)setAppController: (AppController)appCont { appController = appCont; } -(AppController)appController { return appController; } -(void)scrollWheel:(CPEvent)anEvent { [self considerNotifying]; [super scrollWheel:anEvent]; } -(void)considerNotifying { var scroller = [self verticalScroller]; var position = [scroller floatValue]; if (position > .8 && recievedAdditional) { [[self appController] retrieveAdditional]; recievedAdditional = NO; } } -(void)clearResults { images = [[CPArray alloc] init]; } -(void)setImages: (CPArray)anArray { var recievedAdditional = YES; var newResults = eval(anArray); [images addObjectsFromArray:newResults]; [collectionView setContent:[]]; [collectionView setContent:images]; } -(CPArray)images { return images; } -(void)mouseDown(CPEvent)anEvent { alert("mouse down!"); } @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } -(void)setSelected:(BOOL)flag { if (!flag) return; var cv = [self collectionView]; - var window = [[CPPanel alloc] initWithContentRect:CGRectMake(100,100,300,500) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; + var window = [[CPPanel alloc] initWithContentRect:CGRectMake(100,100,300,300) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; var contentView = [window contentView]; - var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(20,20,150,150) data:dict image:image]; + var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(0,0,300,300) data:dict image:image]; [[window contentView] addSubview:aView]; [window orderFront:self]; } @end
lethain/mahou
4c18726997a837271a9a45fd9f8153a27329caed
Now only displaying the selected image, not multiple.
diff --git a/static/WLImageDisplayView.j b/static/WLImageDisplayView.j new file mode 100644 index 0000000..eea4975 --- /dev/null +++ b/static/WLImageDisplayView.j @@ -0,0 +1,44 @@ +import <Foundation/CPObject.j> +import "WLURLLabel.j" + +@implementation WLImageDisplayView : CPView { + CPDictionary data; +} + +-(id)initWithFrame:aFrame data: (CPDictionary)aDict image: (CPImage)anImage { + self = [super initWithFrame:aFrame]; + data = aDict; + + var imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; + [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; + [imageView setImageScaling: CPScaleProportionally]; + [imageView setHasShadow:YES]; + [imageView setImage:anImage]; + + + // height, width, format + // title, clickurl + // abstract + + + + [self addSubview:imageView]; + [self addSubview:[self makeTitleLabel]]; + return self; +} + +-(WLURLLabel)makeTitleLabel { + var fieldFrame = CGRectMake(20,180,200,30); + var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; + + alert(data.title); + [field setStringValue:data.title]; + [field setUrl:data.clickurl]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; + [field setTextColor:[CPColor whiteColor]]; + //[field sizeToFit]; + return field; +} + +@end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index 9afea8a..ee8ed86 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,104 +1,112 @@ import <Foundation/CPObject.j> import "AppController.j" +import "WLImageDisplayView.j" @implementation WLImageResultsView : CPScrollView { CPCollectionView collectionView; CPArray images; AppController appController; BOOL recievedAdditional; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; var photoItem = [[PhotoCell alloc] init]; collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [collectionView setDelegate:self]; [collectionView setItemPrototype:photoItem]; [collectionView setMinItemSize:CGSizeMake(150, 150)]; [collectionView setMaxItemSize:CGSizeMake(150, 150)]; [collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:collectionView]; [self setAutohidesScrollers:YES]; [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; return self; } -(void)setAppController: (AppController)appCont { appController = appCont; } -(AppController)appController { return appController; } -(void)scrollWheel:(CPEvent)anEvent { [self considerNotifying]; [super scrollWheel:anEvent]; } -(void)considerNotifying { var scroller = [self verticalScroller]; var position = [scroller floatValue]; if (position > .8 && recievedAdditional) { [[self appController] retrieveAdditional]; recievedAdditional = NO; } } -(void)clearResults { images = [[CPArray alloc] init]; } -(void)setImages: (CPArray)anArray { var recievedAdditional = YES; var newResults = eval(anArray); [images addObjectsFromArray:newResults]; [collectionView setContent:[]]; [collectionView setContent:images]; } -(CPArray)images { return images; } -(void)mouseDown(CPEvent)anEvent { alert("mouse down!"); } @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } -(void)setSelected:(BOOL)flag { - alert("selected!"); + if (!flag) return; + var cv = [self collectionView]; + var window = [[CPPanel alloc] initWithContentRect:CGRectMake(100,100,300,500) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; + var contentView = [window contentView]; + + var aView = [[WLImageDisplayView alloc] initWithFrame:CGRectMake(20,20,150,150) data:dict image:image]; + [[window contentView] addSubview:aView]; + [window orderFront:self]; } @end
lethain/mahou
fd6bf20c5e38b581dff0fbe3608c1049f9f359d7
Now rerieves additional photo results as necessary.
diff --git a/main.py b/main.py index 9fd87e3..0770dea 100755 --- a/main.py +++ b/main.py @@ -1,56 +1,57 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. __author__ = "Vik Singh ([email protected])" import logging import wsgiref.handlers from google.appengine.ext import webapp from yos.crawl.rest import download from yos.util import console from yos.boss import ysearch from yos.yql import db import simplejson class ImageSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) - data = ysearch.search(query,vertical="images",count=20) + offset = int(console.strfix(self.request.get("offset"))) + data = ysearch.search(query,vertical="images",count=20,start=offset); images = db.create(data=data) serialized = simplejson.dumps(images.rows) self.response.out.write(serialized) class RootHandler(webapp.RequestHandler): def get(self): self.redirect(ROOT_REDIRECT) def main(): logging.getLogger().setLevel(logging.DEBUG) application = webapp.WSGIApplication([('/', RootHandler), ('/search/images', ImageSearchHandler), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() diff --git a/static/AppController.j b/static/AppController.j index d8adca1..c3cb90a 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,131 +1,131 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" import "WLImageResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; WLImageResultsView imageResultsView; CPArray results; int offset; CPString search; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(search:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } - (void)search:(id)sender { offset = 0; search = [searchField stringValue]; [imageResultsView clearResults]; [self searchYahooImagesFor:search withOffset:offset]; } -(void)retrieveAdditional { offset += 20; [self searchYahooImagesFor:search withOffset:offset]; } -(void)searchYahooImagesFor: (CPString)aString withOffset: (int)aNumber { - var query = "/search/images?query="+encodeURIComponent(aString); + var query = "/search/images?query="+encodeURIComponent(aString)+"&offset="+encodeURIComponent(aNumber); var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { [imageResultsView setImages:data]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { alert("error: " + error); } -(void)connectionDidFinishLoading:(CPURLConnection)connection {} /* -(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { alert("response: " + response); } */ -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; [field setStringValue:@"Mahou by Will Larson"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; [imageResultsView setAppController:self]; [contentView addSubview:imageResultsView]; } @end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index 92e768f..9afea8a 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,101 +1,104 @@ import <Foundation/CPObject.j> import "AppController.j" @implementation WLImageResultsView : CPScrollView { CPCollectionView collectionView; CPArray images; AppController appController; + BOOL recievedAdditional; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; var photoItem = [[PhotoCell alloc] init]; collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [collectionView setDelegate:self]; [collectionView setItemPrototype:photoItem]; [collectionView setMinItemSize:CGSizeMake(150, 150)]; [collectionView setMaxItemSize:CGSizeMake(150, 150)]; [collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:collectionView]; [self setAutohidesScrollers:YES]; [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; return self; } -(void)setAppController: (AppController)appCont { appController = appCont; } -(AppController)appController { return appController; } -(void)scrollWheel:(CPEvent)anEvent { [self considerNotifying]; [super scrollWheel:anEvent]; } -(void)considerNotifying { var scroller = [self verticalScroller]; var position = [scroller floatValue]; - if (position > .8) { + if (position > .8 && recievedAdditional) { [[self appController] retrieveAdditional]; + recievedAdditional = NO; + } } -(void)clearResults { images = [[CPArray alloc] init]; } -(void)setImages: (CPArray)anArray { + var recievedAdditional = YES; var newResults = eval(anArray); - alert(newResults); [images addObjectsFromArray:newResults]; [collectionView setContent:[]]; [collectionView setContent:images]; } -(CPArray)images { return images; } -(void)mouseDown(CPEvent)anEvent { alert("mouse down!"); } @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } -(void)setSelected:(BOOL)flag { alert("selected!"); } @end
lethain/mahou
c8d70d8cff469baaa0770e8e836830832472a40c
Now grabbing additional images as necessary, but grabbing too many too quickly.
diff --git a/static/AppController.j b/static/AppController.j index 9e0293b..d8adca1 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,117 +1,131 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" import "WLImageResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; WLImageResultsView imageResultsView; + CPArray results; + int offset; + CPString search; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(search:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } - (void)search:(id)sender { - [self searchYahooImagesFor:[searchField stringValue]]; + offset = 0; + search = [searchField stringValue]; + [imageResultsView clearResults]; + [self searchYahooImagesFor:search withOffset:offset]; } --(void)searchYahooImagesFor: (CPString)aString { +-(void)retrieveAdditional { + offset += 20; + [self searchYahooImagesFor:search withOffset:offset]; +} + +-(void)searchYahooImagesFor: (CPString)aString withOffset: (int)aNumber { var query = "/search/images?query="+encodeURIComponent(aString); var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } + + -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { [imageResultsView setImages:data]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { alert("error: " + error); } -(void)connectionDidFinishLoading:(CPURLConnection)connection {} /* -(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { alert("response: " + response); } */ -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; [field setStringValue:@"Mahou by Will Larson"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; + [imageResultsView setAppController:self]; [contentView addSubview:imageResultsView]; } @end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j index 6b75f90..92e768f 100644 --- a/static/WLImageResultsView.j +++ b/static/WLImageResultsView.j @@ -1,67 +1,101 @@ import <Foundation/CPObject.j> +import "AppController.j" @implementation WLImageResultsView : CPScrollView { CPCollectionView collectionView; CPArray images; + AppController appController; } -(id)initWithFrame:aFrame { self = [super initWithFrame:aFrame]; var photoItem = [[PhotoCell alloc] init]; collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; [collectionView setDelegate:self]; [collectionView setItemPrototype:photoItem]; [collectionView setMinItemSize:CGSizeMake(150, 150)]; [collectionView setMaxItemSize:CGSizeMake(150, 150)]; [collectionView setAutoresizingMask: CPViewWidthSizable]; [self setDocumentView:collectionView]; [self setAutohidesScrollers:YES]; [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; return self; } +-(void)setAppController: (AppController)appCont { + appController = appCont; +} +-(AppController)appController { + return appController; +} + +-(void)scrollWheel:(CPEvent)anEvent { + [self considerNotifying]; + [super scrollWheel:anEvent]; +} + +-(void)considerNotifying { + var scroller = [self verticalScroller]; + var position = [scroller floatValue]; + if (position > .8) { + [[self appController] retrieveAdditional]; + } +} + +-(void)clearResults { + images = [[CPArray alloc] init]; +} + -(void)setImages: (CPArray)anArray { - images = eval(anArray); + var newResults = eval(anArray); + alert(newResults); + [images addObjectsFromArray:newResults]; + [collectionView setContent:[]]; [collectionView setContent:images]; } -(CPArray)images { return images; } + +-(void)mouseDown(CPEvent)anEvent { + alert("mouse down!"); +} + @end @implementation PhotoCell : CPCollectionViewItem { CPImage image; CPImageView imageView; CPDictionary dict; } -(void)setRepresentedObject: (CPDictionary)aDict { dict = aDict; if (!imageView) { imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; [imageView setImageScaling: CPScaleProportionally]; [imageView setHasShadow:YES]; [self setView:imageView]; } if (image) [image setDelegate:nil]; image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; [image setDelegate:self]; if([image loadStatus] == CPImageLoadStatusCompleted) [imageView setImage: image]; else [imageView setImage: nil]; } - (void)imageDidLoad:(CPImage)anImage { [imageView setImage: anImage]; } -(void)setSelected:(BOOL)flag { alert("selected!"); } @end
lethain/mahou
2e5cd3bebce4a4c9e73b1a85d7dc6ed41c250bb3
Now successfully loading images.
diff --git a/app.yaml b/app.yaml index 02f20af..1733b8c 100644 --- a/app.yaml +++ b/app.yaml @@ -1,16 +1,18 @@ application: mahou version: 1 runtime: python api_version: 1 handlers: +- url: /search/.* + script: main.py + - url: / static_files: static/index.html upload: static/index.html - url: / static_dir: static -- url: /.* - script: main.py + diff --git a/main.py b/main.py index 10236b8..9fd87e3 100755 --- a/main.py +++ b/main.py @@ -1,98 +1,56 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. __author__ = "Vik Singh ([email protected])" import logging import wsgiref.handlers from google.appengine.ext import webapp from yos.crawl.rest import download from yos.util import console -from whenqa import whensearch -from wwwqa import wwwsearch +from yos.boss import ysearch +from yos.yql import db -SERP_TEMPLATE = "<html><head><title>Q&A: %s</title><body>" \ - "&nbsp;<font size=\"2\" face=\"arial\"><b><a href=\"http://zooie.wordpress.com\">" \ - "learn more</a></b>" \ - "<center><br/><br/>%s<br/><br/><br/>" \ - "<a href=\"/qa?query=who+is+brad+pitt+married+to\">" \ - "who is brad pitt married to</a><br/>" \ - "<a href=\"/qa?query=who+will+win+the+presidential+election\">" \ - "who will win the presidential election</a><br/>" \ - "<a href=\"/qa?query=who+plays+ari+in+entourage\">" \ - "who plays ari in entourage</a><br/>" \ - "<a href=\"/qa?query=when+did+jfk+get+assasinated\">" \ - "when did jfk get assasinated</a><br/>" \ - "<a href=\"/qa?query=who+invented+the+light+bulb\">" \ - "who invented the light bulb</a><br/>" \ - "<a href=\"/qa?query=what+company+does+jerry+yang+work+at\">" \ - "what company does jerry yang work at</a><br/>" \ - "<a href=\"/qa?query=when+was+britney+spears+born\">" \ - "when was britney spears born</a><br/>" \ - "<a href=\"/qa?query=when+did+microsoft+ipo\">" \ - "when did microsoft ipo</a><br/>" \ - "</font></center></body></head></html>" - -ANSW_TEMPLATE = "<br/><font size=\"3\"><form name=\"input\" action=\"qa\" method=\"get\">" \ - "<input type=\"text\" name=\"query\" size=44 value=\"%s\">&nbsp;&nbsp;" \ - "<input type=\"submit\" value=\"?\"></form><br/>%s</font>" -WHEN_TEMPLATE = "<b>Month:</b>&nbsp;%s&nbsp;&nbsp;<b>Year:</b>&nbsp;%s" -WWW_TEMPLATE = "<b>%s</b>" - -ROOT_REDIRECT = "/qa?query=when+did+yahoo+ipo" -NO_QUERY = "why didn't you provide a question" - -def do_when(query): - month, year = whensearch(query) - answer = ANSW_TEMPLATE % (query, WHEN_TEMPLATE % (month, year)) - return SERP_TEMPLATE % (query, answer) - -def do_www(query): - phrase = wwwsearch(query) - answer = ANSW_TEMPLATE % (query, WWW_TEMPLATE % (phrase)) - return SERP_TEMPLATE % (query, answer) - -class QAHandler(webapp.RequestHandler): +import simplejson +class ImageSearchHandler(webapp.RequestHandler): def get(self): query = console.strfix(self.request.get("query")) - qt = query.split() - if len(qt) == 0: - page = do_www(NO_QUERY) - elif qt[0].lower() == "when": - page = do_when(query) - else: - page = do_www(query) - self.response.out.write(page) + data = ysearch.search(query,vertical="images",count=20) + images = db.create(data=data) + serialized = simplejson.dumps(images.rows) + self.response.out.write(serialized) class RootHandler(webapp.RequestHandler): def get(self): self.redirect(ROOT_REDIRECT) def main(): logging.getLogger().setLevel(logging.DEBUG) application = webapp.WSGIApplication([('/', RootHandler), - ('/qa', QAHandler)], + ('/search/images', ImageSearchHandler), + ], + debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() diff --git a/static/AppController.j b/static/AppController.j index dbc3c82..9e0293b 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,136 +1,117 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" +import "WLImageResultsView.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; - CPCollectionView photosCollectionView; + WLImageResultsView imageResultsView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(search:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } - (void)search:(id)sender { [self searchYahooImagesFor:[searchField stringValue]]; } -(void)searchYahooImagesFor: (CPString)aString { - var query = "/search/images/?query="+encodeURIComponent(aString); + var query = "/search/images?query="+encodeURIComponent(aString); var request = [CPURLRequest requestWithURL:query]; var connection = [CPURLConnection connectionWithRequest:request delegate:self]; [connection start]; } -(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { - alert("recieved: " + data); + [imageResultsView setImages:data]; } - (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error { alert("error: " + error); } --(void)connectionDidFinishLoading:(CPURLConnection)connection { - alert("Finished loading"); -} +-(void)connectionDidFinishLoading:(CPURLConnection)connection {} /* -(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { alert("response: " + response); } */ -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; [field setStringValue:@"Mahou by Will Larson"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; - - var photoItem = [[CPCollectionViewItem alloc] init]; - [photoItem setView:[[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); - - var scrollView = [[CPScrollView alloc] initWithFrame:scrollViewFrame]; - photosCollectionView = [[CPCollectionView alloc] initWithFrame:CGRectMakeZero()]; - [photosCollectionView setDelegate:self]; - [photosCollectionView setItemPrototype:photoItem]; - - [photosCollectionView setMinItemSize:CGSizeMake(150, 150)]; - [photosCollectionView setMaxItemSize:CGSizeMake(150, 150)]; - [photosCollectionView setAutoresizingMask: CPViewWidthSizable]; - - [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; - //[searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; - [scrollView setDocumentView: photosCollectionView]; - [scrollView setAutohidesScrollers: YES]; - - [[scrollView contentView] setBackgroundColor:[CPColor colorWithCalibratedWhite:0.25 alpha:1.0]]; - - [contentView addSubview:scrollView]; + imageResultsView = [[WLImageResultsView alloc] initWithFrame:scrollViewFrame]; + [imageResultsView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; + [contentView addSubview:imageResultsView]; } @end diff --git a/static/WLImageResultsView.j b/static/WLImageResultsView.j new file mode 100644 index 0000000..6b75f90 --- /dev/null +++ b/static/WLImageResultsView.j @@ -0,0 +1,67 @@ +import <Foundation/CPObject.j> + +@implementation WLImageResultsView : CPScrollView { + CPCollectionView collectionView; + CPArray images; +} + +-(id)initWithFrame:aFrame { + self = [super initWithFrame:aFrame]; + var photoItem = [[PhotoCell alloc] init]; + collectionView = [[CPCollectionView alloc] initWithFrame:aFrame]; + [collectionView setDelegate:self]; + [collectionView setItemPrototype:photoItem]; + [collectionView setMinItemSize:CGSizeMake(150, 150)]; + [collectionView setMaxItemSize:CGSizeMake(150, 150)]; + [collectionView setAutoresizingMask: CPViewWidthSizable]; + [self setDocumentView:collectionView]; + [self setAutohidesScrollers:YES]; + [self setBackgroundColor:[CPColor colorWithCalibratedWhite:0.4 alpha:1.0]]; + return self; +} + +-(void)setImages: (CPArray)anArray { + images = eval(anArray); + [collectionView setContent:images]; +} +-(CPArray)images { + return images; +} +@end + +@implementation PhotoCell : CPCollectionViewItem { + CPImage image; + CPImageView imageView; + CPDictionary dict; +} + +-(void)setRepresentedObject: (CPDictionary)aDict { + dict = aDict; + if (!imageView) { + imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]; + [imageView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable]; + [imageView setImageScaling: CPScaleProportionally]; + [imageView setHasShadow:YES]; + [self setView:imageView]; + } + + if (image) + [image setDelegate:nil]; + + image = [[CPImage alloc] initWithContentsOfFile:dict.thumbnail_url]; + [image setDelegate:self]; + if([image loadStatus] == CPImageLoadStatusCompleted) + [imageView setImage: image]; + else + [imageView setImage: nil]; +} + +- (void)imageDidLoad:(CPImage)anImage { + [imageView setImage: anImage]; +} + +-(void)setSelected:(BOOL)flag { + alert("selected!"); +} + +@end
lethain/mahou
a6e77ec1afaf1a405cc09d84670c9e47bb5d3faf
Stubbed out sending and recieving data.
diff --git a/static/AppController.j b/static/AppController.j index de5317b..dbc3c82 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,113 +1,136 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; CPCollectionView photosCollectionView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; - [button setAction:@selector(swap:)]; + [button setAction:@selector(search:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } +- (void)search:(id)sender { + [self searchYahooImagesFor:[searchField stringValue]]; +} + +-(void)searchYahooImagesFor: (CPString)aString { + var query = "/search/images/?query="+encodeURIComponent(aString); + var request = [CPURLRequest requestWithURL:query]; + var connection = [CPURLConnection connectionWithRequest:request delegate:self]; + [connection start]; +} + +-(void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data { + alert("recieved: " + data); +} + +- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPString)error +{ + alert("error: " + error); +} + +-(void)connectionDidFinishLoading:(CPURLConnection)connection { + alert("Finished loading"); +} + +/* +-(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { + alert("response: " + response); +} +*/ + -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; [field setStringValue:@"Mahou by Will Larson"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var photoItem = [[CPCollectionViewItem alloc] init]; [photoItem setView:[[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); var scrollView = [[CPScrollView alloc] initWithFrame:scrollViewFrame]; photosCollectionView = [[CPCollectionView alloc] initWithFrame:CGRectMakeZero()]; [photosCollectionView setDelegate:self]; [photosCollectionView setItemPrototype:photoItem]; [photosCollectionView setMinItemSize:CGSizeMake(150, 150)]; [photosCollectionView setMaxItemSize:CGSizeMake(150, 150)]; [photosCollectionView setAutoresizingMask: CPViewWidthSizable]; [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; //[searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; [scrollView setDocumentView: photosCollectionView]; [scrollView setAutohidesScrollers: YES]; [[scrollView contentView] setBackgroundColor:[CPColor colorWithCalibratedWhite:0.25 alpha:1.0]]; [contentView addSubview:scrollView]; } - - -- (void)swap:(id)sender -{ - -} - @end
lethain/mahou
f35bd0913e54fc4c94b7820049da6f4fd9baeb0f
Added CPJSONConnection.j file form Flickr cappuccino examples.
diff --git a/static/CPJSONPConnection.j b/static/CPJSONPConnection.j new file mode 100644 index 0000000..d39d245 --- /dev/null +++ b/static/CPJSONPConnection.j @@ -0,0 +1,86 @@ + +import <Foundation/CPObject.j> + +CPJSONPConnectionCallbacks = {}; + +@implementation CPJSONPConnection : CPObject +{ + CPURLRequest _request; + id _delegate; + + CPString _callbackParameter; + DOMElement _scriptTag; +} + ++ (CPData)sendRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate +{ + return [[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate startImmediately:YES];; +} + +- (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate +{ + return [self initWithRequest:aRequest callback:aString delegate:aDelegate startImmediately: NO]; +} + +- (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately +{ + self = [super init]; + + _request = aRequest; + _delegate = aDelegate; + + _callbackParameter = aString; + + CPJSONPConnectionCallbacks["callback"+[self hash]] = function(data) + { + [_delegate connection:self didReceiveData:data]; + [self removeScriptTag]; + }; + + if(shouldStartImmediately) + [self start]; + + return self; +} + +- (void)start +{ + try + { + var head = document.getElementsByTagName("head").item(0); + + var source = [_request URL]; + source += (source.indexOf('?') < 0) ? "?" : "&"; + source += _callbackParameter+"=CPJSONPConnectionCallbacks.callback"+[self hash]; + + _scriptTag = document.createElement("script"); + _scriptTag.setAttribute("type", "text/javascript"); + _scriptTag.setAttribute("charset", "utf-8"); + _scriptTag.setAttribute("src", source); + + head.appendChild(_scriptTag); + } + catch (exception) + { + [_delegate connection: self didFailWithError: exception]; + [self removeScriptTag]; + } +} + +- (void)removeScriptTag +{ + var head = document.getElementsByTagName("head").item(0); + + if(_scriptTag.parentNode == head) + head.removeChild(_scriptTag); + + CPJSONPConnectionCallbacks["callback"+[self hash]] = nil; + delete CPJSONPConnectionCallbacks["callback"+[self hash]]; +} + +- (void)cancel +{ + [self removeScriptTag]; +} + +@end \ No newline at end of file
lethain/mahou
ed54ed41416fb3a5074c32427112661d8cc90c67
Better centering for attribution label.
diff --git a/static/AppController.j b/static/AppController.j index f2b216e..de5317b 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,112 +1,113 @@ import <Foundation/CPObject.j> import "WLTextField.j" import "WLURLLabel.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; CPCollectionView photosCollectionView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(swap:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [self setupAttributionLabel:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } -(void)setupAttributionLabel: (CPView)contentView { var bounds = [contentView bounds]; - var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0,CGRectGetMaxY(bounds)-100,200,30); + var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0-60,CGRectGetMaxY(bounds)-100,200,30); var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; [field setStringValue:@"Mahou by Will Larson"]; [field setUrl:@"http://lethain.com/"]; [field setFont:[CPFont boldSystemFontOfSize:12.0]]; [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; [field setTextColor:[CPColor whiteColor]]; + [field sizeToFit]; [contentView addSubview:field]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var photoItem = [[CPCollectionViewItem alloc] init]; [photoItem setView:[[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, CGRectGetHeight(bounds)-200); var scrollView = [[CPScrollView alloc] initWithFrame:scrollViewFrame]; photosCollectionView = [[CPCollectionView alloc] initWithFrame:CGRectMakeZero()]; [photosCollectionView setDelegate:self]; [photosCollectionView setItemPrototype:photoItem]; [photosCollectionView setMinItemSize:CGSizeMake(150, 150)]; [photosCollectionView setMaxItemSize:CGSizeMake(150, 150)]; [photosCollectionView setAutoresizingMask: CPViewWidthSizable]; [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; //[searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; [scrollView setDocumentView: photosCollectionView]; [scrollView setAutohidesScrollers: YES]; [[scrollView contentView] setBackgroundColor:[CPColor colorWithCalibratedWhite:0.25 alpha:1.0]]; [contentView addSubview:scrollView]; } - (void)swap:(id)sender { } @end
lethain/mahou
16254c6bb224327a34726a92c40d83ae3c4a7099
Added WLURLLabel.j which allows clickable links, and added a small self link at bototm of app.
diff --git a/static/AppController.j b/static/AppController.j index 0fc3d72..f2b216e 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,96 +1,112 @@ import <Foundation/CPObject.j> import "WLTextField.j" - +import "WLURLLabel.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; CPCollectionView photosCollectionView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { + var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(swap:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; + [self setupAttributionLabel:contentView]; + [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } +-(void)setupAttributionLabel: (CPView)contentView { + var bounds = [contentView bounds]; + var fieldFrame = CGRectMake(CGRectGetWidth(bounds)/2.0,CGRectGetMaxY(bounds)-100,200,30); + var field = [[WLURLLabel alloc] initWithFrame:fieldFrame]; + + [field setStringValue:@"Mahou by Will Larson"]; + [field setUrl:@"http://lethain.com/"]; + [field setFont:[CPFont boldSystemFontOfSize:12.0]]; + [field setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin]; + [field setTextColor:[CPColor whiteColor]]; + [contentView addSubview:field]; +} + -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var photoItem = [[CPCollectionViewItem alloc] init]; [photoItem setView:[[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]]; var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, - 350); + CGRectGetHeight(bounds)-200); var scrollView = [[CPScrollView alloc] initWithFrame:scrollViewFrame]; photosCollectionView = [[CPCollectionView alloc] initWithFrame:CGRectMakeZero()]; [photosCollectionView setDelegate:self]; [photosCollectionView setItemPrototype:photoItem]; [photosCollectionView setMinItemSize:CGSizeMake(150, 150)]; [photosCollectionView setMaxItemSize:CGSizeMake(150, 150)]; [photosCollectionView setAutoresizingMask: CPViewWidthSizable]; [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; //[searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; [scrollView setDocumentView: photosCollectionView]; [scrollView setAutohidesScrollers: YES]; - [[scrollView contentView] setBackgroundColor:[CPColor blackColor]]; + [[scrollView contentView] setBackgroundColor:[CPColor colorWithCalibratedWhite:0.25 alpha:1.0]]; [contentView addSubview:scrollView]; } - (void)swap:(id)sender { } @end diff --git a/static/Info.plist b/static/Info.plist index 92ab8b5..5c1d4d7 100644 --- a/static/Info.plist +++ b/static/Info.plist @@ -1,12 +1,12 @@ <?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>CPApplicationDelegateClass</key> <string>AppController</string> <key>CPBundleName</key> - <string>Hello World</string> + <string>Mahou</string> <key>CPPrincipalClass</key> <string>CPApplication</string> </dict> </plist> diff --git a/static/WLURLLabel.j b/static/WLURLLabel.j new file mode 100644 index 0000000..3b4806f --- /dev/null +++ b/static/WLURLLabel.j @@ -0,0 +1,21 @@ +import <Foundation/CPObject.j> +import <AppKit/CPTextField.j> + +@implementation WLURLLabel : CPTextField +{ + CPString url; +} + +-(void)mouseDown:(CPEvent)anEvent { + window.open([self url]); +} + +-(void)setUrl: (CPString)aString { + url = aString; +} + +-(CPString)url { + return url; +} + +@end diff --git a/static/index.html b/static/index.html index 61892d8..5fbe076 100644 --- a/static/index.html +++ b/static/index.html @@ -1,36 +1,36 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang = "en" lang = "en"> <!-- // // index.html // Viewer // // Created by Ross Boucher on 5/19/2008. // Copyright 2005 - 2008, 280 North, Inc. All rights reserved. // --> <head> - <title>Hello World</title> + <title>Mahou</title> <script src = "Frameworks/Objective-J/Objective-J.js" type = "text/javascript"></script> <script type = "text/javascript"> objj_import("main.j", YES, function() { main(); }); </script> </head> <body> <div style="margin-top: 110px;"> <center> <img src = "Frameworks/AppKit/Resources/CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif" /> </center> </div> </body> </html> \ No newline at end of file
lethain/mahou
7753269c0c89b6baa8d13bbcb4318165132036db
Tweaked position of textfield for better resizing.
diff --git a/static/AppController.j b/static/AppController.j index ce8b1b5..0fc3d72 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,103 +1,96 @@ import <Foundation/CPObject.j> import "WLTextField.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; CPCollectionView photosCollectionView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; - var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+40,10,400,34); + var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+20,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(swap:)]; [contentView addSubview:button]; [self setupPhotosCollectionView:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } -(void)setupPhotosCollectionView: (CPView)contentView { var bounds = [contentView bounds]; var photoItem = [[CPCollectionViewItem alloc] init]; [photoItem setView:[[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]]; - - - //[searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; - - //var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+40,10,400,34); - - var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, CGRectGetMinY(bounds)+100, CGRectGetWidth(bounds)-150, 350); var scrollView = [[CPScrollView alloc] initWithFrame:scrollViewFrame]; photosCollectionView = [[CPCollectionView alloc] initWithFrame:CGRectMakeZero()]; [photosCollectionView setDelegate:self]; [photosCollectionView setItemPrototype:photoItem]; [photosCollectionView setMinItemSize:CGSizeMake(150, 150)]; [photosCollectionView setMaxItemSize:CGSizeMake(150, 150)]; [photosCollectionView setAutoresizingMask: CPViewWidthSizable]; [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; //[searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; [scrollView setDocumentView: photosCollectionView]; [scrollView setAutohidesScrollers: YES]; [[scrollView contentView] setBackgroundColor:[CPColor blackColor]]; [contentView addSubview:scrollView]; } - (void)swap:(id)sender { } @end
lethain/mahou
b7fe8fcf8042831e0edf88f26a3d719c1565b68b
Displaying collection view.
diff --git a/static/AppController.j b/static/AppController.j index 4af2f6b..ce8b1b5 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,67 +1,103 @@ import <Foundation/CPObject.j> import "WLTextField.j" @implementation AppController : CPObject { WLTextField searchField; CPButton button; + CPCollectionView photosCollectionView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+40,10,400,34); searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; - //[searchField setAlignment:CPCenterTextAlignment]; - //[searchField setStringValue:@"type your search here"]; [searchField setPlaceholderString:@"type your search here"]; [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; - //[searchField sizeToFit]; - - [searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; + [searchField setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; - [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin|CPViewMinYMargin|CPViewMaxYMargin]; + [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; - [button setAction:@selector(swap:)]; + [button setAction:@selector(swap:)]; [contentView addSubview:button]; - + + [self setupPhotosCollectionView:contentView]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } +-(void)setupPhotosCollectionView: (CPView)contentView { + var bounds = [contentView bounds]; + + var photoItem = [[CPCollectionViewItem alloc] init]; + [photoItem setView:[[CPImageView alloc] initWithFrame:CGRectMake(0,0,150,150)]]; + + + //[searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; + + //var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+40,10,400,34); + + + var scrollViewFrame = CGRectMake(CGRectGetMinX(bounds)+75, + CGRectGetMinY(bounds)+100, + CGRectGetWidth(bounds)-150, + 350); + + var scrollView = [[CPScrollView alloc] initWithFrame:scrollViewFrame]; + photosCollectionView = [[CPCollectionView alloc] initWithFrame:CGRectMakeZero()]; + [photosCollectionView setDelegate:self]; + [photosCollectionView setItemPrototype:photoItem]; + + [photosCollectionView setMinItemSize:CGSizeMake(150, 150)]; + [photosCollectionView setMaxItemSize:CGSizeMake(150, 150)]; + [photosCollectionView setAutoresizingMask: CPViewWidthSizable]; + + [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable]; + //[searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; + [scrollView setDocumentView: photosCollectionView]; + [scrollView setAutohidesScrollers: YES]; + + [[scrollView contentView] setBackgroundColor:[CPColor blackColor]]; + + [contentView addSubview:scrollView]; +} + + + - (void)swap:(id)sender { } @end
lethain/mahou
a801e6428b8ee4daf002f6f74e0288a96abfd8cf
Now have placeholder textfield.
diff --git a/static/AppController.j b/static/AppController.j index d4e1192..4af2f6b 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,64 +1,67 @@ import <Foundation/CPObject.j> +import "WLTextField.j" @implementation AppController : CPObject { - CPTextField searchField; + WLTextField searchField; CPButton button; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], contentView = [theWindow contentView]; [contentView setBackgroundColor: [CPColor grayColor]]; var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+40,10,400,34); - searchField = [[CPTextField alloc] initWithFrame:searchFieldFrame]; + searchField = [[WLTextField alloc] initWithFrame:searchFieldFrame]; //[searchField setAlignment:CPCenterTextAlignment]; - [searchField setStringValue:@"Type your search here"]; + //[searchField setStringValue:@"type your search here"]; + [searchField setPlaceholderString:@"type your search here"]; + [searchField setStringValue:[searchField placeholderString]]; [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; [searchField setEditable:YES]; [searchField setSelectable:YES]; [searchField setBordered:YES]; [searchField setBezeled:YES]; [searchField setBezelStyle:CPTextFieldRoundedBezel]; [searchField setBackgroundColor: [CPColor whiteColor]]; //[searchField sizeToFit]; [searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; [contentView addSubview:searchField]; var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, CGRectGetMinY([searchField frame])-16, 64,64); button = [[CPButton alloc] initWithFrame:buttonFrame]; [button setImage:image]; [button setAlternateImage:altImage]; [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin|CPViewMinYMargin|CPViewMaxYMargin]; [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(swap:)]; [contentView addSubview:button]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } - (void)swap:(id)sender { } @end diff --git a/static/WLTextField.j b/static/WLTextField.j new file mode 100644 index 0000000..88abffe --- /dev/null +++ b/static/WLTextField.j @@ -0,0 +1,32 @@ +import <Foundation/CPObject.j> +import <AppKit/CPTextField.j> + +@implementation WLTextField : CPTextField +{ + CPString placeholderString; +} + +-(BOOL)becomeFirstResponder { + if ([[self stringValue] caseInsensitiveCompare:[self placeholderString]]==0) { + [self setStringValue:@""]; + } + return [super becomeFirstResponder]; +} + +-(BOOL)resignFirstResponder { + if ([[self stringValue] caseInsensitiveCompare:@""]==0) { + [self setStringValue:[self placeholderString]]; + } + return [super resignFirstResponder]; +} + +-(void)setPlaceholderString: (CPString)aString { + placeholderString = aString; +} + +-(CPString)placeholderString { + return placeholderString; +} + + +@end
lethain/mahou
a34e21f69603a38d59f118a6e41d1c649430ed6f
Added custom search button icons, search field, etc.
diff --git a/static/AppController.j b/static/AppController.j index d062523..d4e1192 100644 --- a/static/AppController.j +++ b/static/AppController.j @@ -1,43 +1,64 @@ import <Foundation/CPObject.j> @implementation AppController : CPObject { + CPTextField searchField; + CPButton button; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask], - contentView = [theWindow contentView]; + contentView = [theWindow contentView]; + [contentView setBackgroundColor: [CPColor grayColor]]; - var label = [[CPTextField alloc] initWithFrame:CGRectMakeZero()]; + var searchFieldFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0+40,10,400,34); + searchField = [[CPTextField alloc] initWithFrame:searchFieldFrame]; + //[searchField setAlignment:CPCenterTextAlignment]; + [searchField setStringValue:@"Type your search here"]; + [searchField setFont:[CPFont boldSystemFontOfSize:24.0]]; + [searchField setEditable:YES]; + [searchField setSelectable:YES]; + [searchField setBordered:YES]; + [searchField setBezeled:YES]; + [searchField setBezelStyle:CPTextFieldRoundedBezel]; + [searchField setBackgroundColor: [CPColor whiteColor]]; + //[searchField sizeToFit]; - [label setStringValue:@"Hello World!"]; - [label setFont:[CPFont boldSystemFontOfSize:24.0]]; - - [label sizeToFit]; - - [label setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; - [label setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([label frame])) / 2.0, (CGRectGetHeight([contentView bounds]) - CGRectGetHeight([label frame])) / 2.0)]; - - [contentView addSubview:label]; + [searchField setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin]; + [searchField setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([searchField frame])) / 2.5, (CGRectGetMinY([contentView bounds]) + CGRectGetHeight([searchField frame])))]; + + + [contentView addSubview:searchField]; - var buttonFrame = CGRectMake(CGRectGetWidth([contentView bounds])/2.0 - 40, - CGRectGetMaxY([label frame]) + 10, - 80,18); - var button = [[CPButton alloc] initWithFrame:buttonFrame]; + var image = [[CPImage alloc] initWithContentsOfFile:"Resources/searchIcon.png" size:CPSizeMake(64,64)], altImage = [[CPImage alloc] initWithContentsOfFile:"Resources/altSearchIcon.png" size:CPSizeMake(64,64)]; + + var buttonFrame = CGRectMake(CGRectGetMaxX([searchField frame])+8, + CGRectGetMinY([searchField frame])-16, + 64,64); + button = [[CPButton alloc] initWithFrame:buttonFrame]; + [button setImage:image]; + [button setAlternateImage:altImage]; + [button setImagePosition:CPImageOnly]; [button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin|CPViewMinYMargin|CPViewMaxYMargin]; + [button setBordered:NO]; [button setTitle:"search"]; [button setTarget:self]; [button setAction:@selector(swap:)]; [contentView addSubview:button]; [theWindow orderFront:self]; // Uncomment the following line to turn on the standard menu bar. //[CPMenu setMenuBarVisible:YES]; } +- (void)swap:(id)sender +{ + +} + @end diff --git a/static/Resources/altSearchIcon.png b/static/Resources/altSearchIcon.png new file mode 100644 index 0000000..032c585 Binary files /dev/null and b/static/Resources/altSearchIcon.png differ diff --git a/static/Resources/searchIcon.png b/static/Resources/searchIcon.png new file mode 100644 index 0000000..34e4bc9 Binary files /dev/null and b/static/Resources/searchIcon.png differ
lethain/mahou
30f3331c4351ce75c95a501a9020d1d48ccdcd91
Now loading Cappuccino app at /
diff --git a/app.yaml b/app.yaml index bd2234e..02f20af 100644 --- a/app.yaml +++ b/app.yaml @@ -1,10 +1,16 @@ application: mahou version: 1 runtime: python api_version: 1 handlers: -- url: .* - script: main.py -- url: /qa + +- url: / + static_files: static/index.html + upload: static/index.html + +- url: / + static_dir: static + +- url: /.* script: main.py
as3/as3-utils
a4285a1fd1ed2c1fd52518729ef710f618a9b360
added a method to find an ancestor by type or by reference
diff --git a/src/utils/display/findAncestor.as b/src/utils/display/findAncestor.as new file mode 100644 index 0000000..3e0feed --- /dev/null +++ b/src/utils/display/findAncestor.as @@ -0,0 +1,19 @@ +package utils.display +{ + import flash.display.DisplayObject; + + /** + * Search the ancestry for a specific parent object. + * @param child The display object whose parents to check. + * @param ancestor The ancestor to check for. + * @return The ancestor or null. + * @author Mims H. Wright + */ + public function findAncestor(child:DisplayObject, ancestor:DisplayObject):DisplayObject + { + if (child == ancestor) { return ancestor; } + if (child.parent == null) { return null; } + if (child.parent == ancestor) { return ancestor; } + return findAncestor(child.parent, ancestor); + } +} \ No newline at end of file diff --git a/src/utils/display/findAncestorWithType.as b/src/utils/display/findAncestorWithType.as new file mode 100644 index 0000000..0c7790a --- /dev/null +++ b/src/utils/display/findAncestorWithType.as @@ -0,0 +1,18 @@ +package utils.display +{ + import flash.display.DisplayObject; + + /** + * Search the ancestry for a specific parent object. + * @param child The display object whose parents to check. + * @param type The type to check for. Should be a class or interface. + * @return The ancestor or null. + * @author Mims H. Wright + */ + public function findAncestorWithType(child:DisplayObject, type:*):* + { + if (child.parent == null) { return null; } + if (child.parent is type) { return child.parent; } + return findAncestorWithType(child.parent, type); + } +} \ No newline at end of file diff --git a/test/utils/display/FindAncestorTest.as b/test/utils/display/FindAncestorTest.as new file mode 100644 index 0000000..08409d0 --- /dev/null +++ b/test/utils/display/FindAncestorTest.as @@ -0,0 +1,42 @@ +package flexUnitTests +{ + import flash.display.MovieClip; + import flash.display.Shape; + import flash.display.Sprite; + + import org.flexunit.asserts.assertEquals; + import org.flexunit.asserts.assertNull; + + import utils.display.findAncestor; + import utils.display.findAncestorWithType; + + public class FindAncestorTest + { + [Test] + public function findAncestorTest():void + { + var a:MovieClip = new MovieClip(); + var b:Sprite = new Sprite(); + var c:Shape = new Shape(); + + var d:Sprite = new Sprite(); // not in chain + + a.addChild(b); + b.addChild(c); + + assertEquals(findAncestor(c, a), a); + assertEquals(findAncestor(c, b), b); + assertEquals(findAncestor(c, c), c); + + assertNull(findAncestor(a, c)); + assertNull(findAncestor(c, d)); + + assertEquals(findAncestorWithType(c, MovieClip), a); + assertEquals(findAncestorWithType(c, Sprite), b); + + assertNull(findAncestorWithType(c, Shape)); + + } + + } +} \ No newline at end of file
as3/as3-utils
dbb89b86892988b08156a0e5ab7915618999e71b
Added moveTo and moveBy
diff --git a/src/utils/display/moveBy.as b/src/utils/display/moveBy.as new file mode 100644 index 0000000..5d7952e --- /dev/null +++ b/src/utils/display/moveBy.as @@ -0,0 +1,18 @@ +package utils.display +{ + import flash.display.DisplayObject; + + /** + * Moves a display object by a given x and y position. + * x and y parameters are optional and if either is omitted, the current position will not change. + * + * @author Mims Wright + */ + public function moveBy(displayObject:DisplayObject, x:Number = NaN, y:Number = NaN):void + { + if (isNaN(x)) { x = 0; } + if (isNaN(y)) { y = 0; } + displayObject.x += x; + displayObject.y += y; + } +} \ No newline at end of file diff --git a/src/utils/display/moveTo.as b/src/utils/display/moveTo.as new file mode 100644 index 0000000..9e0e420 --- /dev/null +++ b/src/utils/display/moveTo.as @@ -0,0 +1,18 @@ +package utils.display +{ + import flash.display.DisplayObject; + + /** + * Moves a display object to a given x and y position. + * x and y parameters are optional and if either is omitted, the current position will not change. + * + * @author Mims Wright + */ + public function moveTo(displayObject:DisplayObject, x:Number = NaN, y:Number = NaN):void + { + if (isNaN(x)) { x = displayObject.x; } + if (isNaN(y)) { y = displayObject.y; } + displayObject.x = x; + displayObject.y = y; + } +} \ No newline at end of file
as3/as3-utils
e14aab4178c697ef2cdd9c4acfb9b90b326212db
added get position to the right / under functions
diff --git a/src/utils/align/getPositionToTheRightOf.as b/src/utils/align/getPositionToTheRightOf.as new file mode 100644 index 0000000..8f8af46 --- /dev/null +++ b/src/utils/align/getPositionToTheRightOf.as @@ -0,0 +1,21 @@ +package utils.align +{ + import flash.display.DisplayObject; + + import utils.ratio.widthToHeight; + + /** + * Gets the position to the right of an object based on its width and x position + * with an optional gap. + * + * This is useful when you need to cause object B to appear 20px to the right of object A. + * + * B.x = getPositionToTheRightOf(A, 20); + * + * @param displayObject An object to get the position under. + * @param gap An optional amount to space out the position under. + */ + public function getPositionToTheRightOf(displayObject:DisplayObject, gap:int = 0):int { + return displayObject.x + displayObject.width + gap; + } +} \ No newline at end of file diff --git a/src/utils/align/getPositionUnder.as b/src/utils/align/getPositionUnder.as new file mode 100644 index 0000000..e855e84 --- /dev/null +++ b/src/utils/align/getPositionUnder.as @@ -0,0 +1,17 @@ +package utils.align { + import flash.display.DisplayObject; + + /** + * Gets the position under an object based on its height and y position with an optional gap. + * + * This is useful when you need to cause object B to appear 20px below object A. + * + * B.y = getPositionUnder(A, 20); + * + * @param displayObject An object to get the position under. + * @param gap An optional amount to space out the position under. + */ + public function getPositionUnder(displayObject:DisplayObject, gap:int = 0):int { + return displayObject.y + displayObject.height + gap; + } +} \ No newline at end of file
as3/as3-utils
171699020368235c0b8528a0e4663fc02cc61432
Fixed removeAllChildrenByType() which wasn't working
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index 1a97344..a414559 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/display/removeAllChildrenByType.as b/src/utils/display/removeAllChildrenByType.as index 708fae7..4e7f9d0 100644 --- a/src/utils/display/removeAllChildrenByType.as +++ b/src/utils/display/removeAllChildrenByType.as @@ -1,34 +1,42 @@ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * Remove all children of a specific type from a container. * * @example <listing version="3.0"> * var s:Sprite = new Sprite(); * s.addChild(new Shape()); * s.addChild(new Shape()); * s.addChild(new MovieClip()); * s.addChild(new Sprite()); * trace(s.numChildren); // 4 * removeAllChildrenByType(s, Shape); * trace(s.numChildren); // 2 * </listing> * * @param container Container to remove from * @param the type of children to remove * @author John Lindquist */ public function removeAllChildrenByType(container:DisplayObjectContainer, type:Class):void { - for each(var child:DisplayObject in container) - { - if(child is type) - { - container.removeChild(child); + var i:int = 0 + , l:int = container.numChildren + , childrenToRemove:Array = [] + , child:DisplayObject; + + for (;i<l;i+=1) { + child = container.getChildAt(i); + if(child is type) { + childrenToRemove.push(child); } } + + for each (child in childrenToRemove) { + container.removeChild(child); + } } } \ No newline at end of file
as3/as3-utils
d9cb19e8a873be2884c979f6f989374f8bc8832c
Added gcd(), expressAsOdds(), centerWithin()
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index bbd284c..d84b713 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/display/centerWithin.as b/src/utils/display/centerWithin.as new file mode 100644 index 0000000..f2d0ea3 --- /dev/null +++ b/src/utils/display/centerWithin.as @@ -0,0 +1,27 @@ +package utils.display +{ + import flash.display.DisplayObject; + + /** + * Centers a display object within the bounds of another based on each of their sizes. + * Note: does not add the object as a child or add to stage or resize either object. + * + * @param objectToPosition The DisplayObject that will be moved. + * @param withinObject The DisplayObject to position within. If left blank, + * will attempt to use the object's parent. + * + * @author Mims Wright + */ + public function centerWithin(objectToPosition:DisplayObject, withinObject:DisplayObject = null):void { + if (!objectToPosition) { return; } + if (!withinObject) { + if (objectToPosition.parent) { + withinObject = objectToPosition.parent; + } else { + return; + } + } + objectToPosition.x = (withinObject.width - objectToPosition.width)/2; + objectToPosition.y = (withinObject.height - objectToPosition.height)/2; + } +} \ No newline at end of file diff --git a/src/utils/math/expressAsOdds.as b/src/utils/math/expressAsOdds.as new file mode 100644 index 0000000..455cc38 --- /dev/null +++ b/src/utils/math/expressAsOdds.as @@ -0,0 +1,16 @@ +package utils.math +{ + /** + * Expresses chances that an outcome will occur out of a number of total possible outcomes. + * + * @example <pre> + * // number of kings in a deck of cards. + * expressAsOdds(4, 52); // 1:13 + * + * @author Mims Wright + */ + public function expressAsOdds(numberOfChances:int, allPossibleOutcomes:int):String { + var _gcd:int = gcd(numberOfChances, allPossibleOutcomes); + return (numberOfChances / _gcd) + ":" + (allPossibleOutcomes / _gcd); + } +} \ No newline at end of file diff --git a/src/utils/math/gcd.as b/src/utils/math/gcd.as new file mode 100644 index 0000000..ad77304 --- /dev/null +++ b/src/utils/math/gcd.as @@ -0,0 +1,14 @@ +package utils.math +{ + /** + * Returns the greatest common devisor between two ints. + * + * @author Mims Wright + */ + public function gcd(a:int, b:int):int { + if (b == 0) { + return a; + } + return gcd (b, a%b); + } +} \ No newline at end of file diff --git a/src/utils/range/center.as b/src/utils/range/center.as index 5c20497..4a42f95 100644 --- a/src/utils/range/center.as +++ b/src/utils/range/center.as @@ -1,28 +1,29 @@ package utils.range { + // TODO: what is the purpose of this function? Needs documentation. public function center(a:Number, b:Number, c:Number):Number { if ((a > b) && (a > c)) { if (b > c) return b; else return c; } else if ((b > a) && (b > c)) { if (a > c) return a; else return c; } else if (a > b) { return a; } else { return b; } } } \ No newline at end of file
as3/as3-utils
d7166fa9b282decd13763878e3d2af4354e5ca04
Added transformToFitRect. Changed return type of removeChild.
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index 65cb0bc..bbd284c 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/display/removeChild.as b/src/utils/display/removeChild.as index a0d977e..e429e29 100644 --- a/src/utils/display/removeChild.as +++ b/src/utils/display/removeChild.as @@ -1,33 +1,33 @@ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * Removes a child from the parent without throwing errors if the child or parent is null * or if the child isn't a child of the specified parent. * * @param child The child DisplayObject to remove. * @param parent The parent to remove the child from. If none is specified, the function * attempts to get the parent from the child's <code>parent</code> property. - * @returns Boolean True if the child was removed from the parent. False if something prevented it. + * @return DisplayObject The child that was removed. * * @author Mims Wright */ - public function removeChild(child:DisplayObject, parent:DisplayObjectContainer = null):Boolean + public function removeChild(child:DisplayObject, parent:DisplayObjectContainer = null):DisplayObject { if (child) { if (!parent) { if (!child.parent) { // if parent and child.parent are null - return false; + return null; } parent = child.parent; } if (parent == child.parent) { parent.removeChild(child); - return true; + return child; } } - return false; + return null; } } \ No newline at end of file diff --git a/src/utils/display/transformToFitRect.as b/src/utils/display/transformToFitRect.as new file mode 100644 index 0000000..d2c6ff2 --- /dev/null +++ b/src/utils/display/transformToFitRect.as @@ -0,0 +1,18 @@ +package utils.display +{ + import flash.display.DisplayObject; + import flash.geom.Rectangle; + + /** + * Moves and resizes a display object to fit within a rectangle. + * + * @author Mims Wright + */ + public function transformToFitRect(displayObject:DisplayObject, rectangle:Rectangle):void + { + displayObject.x = rectangle.x; + displayObject.y = rectangle.y; + displayObject.width = rectangle.width; + displayObject.height = rectangle.height; + } +} \ No newline at end of file
as3/as3-utils
322a8484fd76733744a9ef371f86a585d1b80793
fixed issue #18
diff --git a/src/utils/string/htmlEncode.as b/src/utils/string/htmlEncode.as index 96c643b..006ce0e 100644 --- a/src/utils/string/htmlEncode.as +++ b/src/utils/string/htmlEncode.as @@ -1,30 +1,31 @@ package utils.string { /** * Encode HTML. */ public function htmlEncode(s:String):String { - s = replace(s, " ", "&nbsp;"); s = replace(s, "&", "&amp;"); + + s = replace(s, " ", "&nbsp;"); s = replace(s, "<", "&lt;"); s = replace(s, ">", "&gt;"); s = replace(s, "™", '&trade;'); s = replace(s, "®", '&reg;'); s = replace(s, "©", '&copy;'); s = replace(s, "€", "&euro;"); s = replace(s, "£", "&pound;"); s = replace(s, "—", "&mdash;"); s = replace(s, "–", "&ndash;"); s = replace(s, "…", "&hellip;"); s = replace(s, "†", "&dagger;"); s = replace(s, "·", "&middot;"); s = replace(s, "µ", "&micro;"); s = replace(s, "«", "&laquo;"); s = replace(s, "»", "&raquo;"); s = replace(s, "•", "&bull;"); s = replace(s, "°", "&deg;"); s = replace(s, '"', "&quot;"); return s; } } \ No newline at end of file
as3/as3-utils
adac1014bf5277bdc13d88ea26fa5d7358b64b9a
Added date.isPast()
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index 5110926..65cb0bc 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/date/isPast.as b/src/utils/date/isPast.as new file mode 100644 index 0000000..fb376a7 --- /dev/null +++ b/src/utils/date/isPast.as @@ -0,0 +1,13 @@ +package utils.date +{ + /** + * Returns true if date is in the past. + * If the date is exactly equal to the current time, it will return false. + * + * @author Mims H. Wright + */ + public function isPast(date:Date):Boolean + { + return (new Date().getTime() - date.getTime()) > 0; + } +} \ No newline at end of file
as3/as3-utils
8b7c26d9f11a7af219e776445fdabb7dcb604411
Added two new date functions
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index 1797641..5110926 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/date/compareDates.as b/src/utils/date/compareDates.as index 4bf4bd3..1af07d4 100644 --- a/src/utils/date/compareDates.as +++ b/src/utils/date/compareDates.as @@ -1,37 +1,37 @@ package utils.date { /** * Compares two dates and returns an integer depending on their relationship. * - * Returns -1 if d1 is greater than d2. - * Returns 1 if d2 is greater than d1. + * Returns -1 if d1 is later than d2. + * Returns 1 if d2 is later than d1. * Returns 0 if both dates are equal. * * @param d1 The date that will be compared to the second date. * @param d2 The date that will be compared to the first date. * * @return An int indicating how the two dates compare. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function compareDates(d1:Date, d2:Date):int { var d1ms:Number = d1.getTime(); var d2ms:Number = d2.getTime(); if (d1ms > d2ms) { return -1; } else if (d1ms < d2ms) { return 1; } else { return 0; } } } \ No newline at end of file diff --git a/src/utils/date/getEarliestDate.as b/src/utils/date/getEarliestDate.as new file mode 100644 index 0000000..25c6675 --- /dev/null +++ b/src/utils/date/getEarliestDate.as @@ -0,0 +1,31 @@ +package utils.date +{ + /** + * Compares dates and returns the latest one. + * + * @param dates that will be compared. + * @return The latest date. + * + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @author Mims H. Wright + */ + public function getEarliestDate(... dates ):Date + { + var earliestDate:Date; + if (dates.length() == 0) { + throw new ArgumentError("Requires at least one argument"); + } + for each (var date:Date in dates) { + if (!earliestDate) { + earliestDate = date; + continue; + } + + if (date.getTime() > earliestDate.getTime()) { + earliestDate = date; + } + } + return earliestDate; + } +} \ No newline at end of file diff --git a/src/utils/date/getLatestDate.as b/src/utils/date/getLatestDate.as new file mode 100644 index 0000000..1e6da01 --- /dev/null +++ b/src/utils/date/getLatestDate.as @@ -0,0 +1,31 @@ +package utils.date +{ + /** + * Compares dates and returns the latest one. + * + * @param dates that will be compared. + * @return The latest date. + * + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @author Mims H. Wright + */ + public function getLatestDate(... dates ):Date + { + var latestDate:Date; + if (dates.length() == 0) { + throw new ArgumentError("Requires at least one argument"); + } + for each (var date:Date in dates) { + if (!latestDate) { + latestDate = date; + continue; + } + + if (date.getTime() > latestDate.getTime()) { + latestDate = date; + } + } + return latestDate; + } +} \ No newline at end of file diff --git a/src/utils/mvc/AbstractView.as b/src/utils/mvc/AbstractView.as index 3b597c8..cf6ced0 100644 --- a/src/utils/mvc/AbstractView.as +++ b/src/utils/mvc/AbstractView.as @@ -1,65 +1,66 @@ package utils.mvc { import flash.display.DisplayObject; import flash.display.MovieClip; /** * A default implementation of IView based on MovieClip. * * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public class AbstractView extends MovieClip implements IView { /** * Constructor. * * @param model The data model that defines this view. * @param controller A specific controller to use (otherwise, the defaultController will be used) */ public function AbstractView ( model:*, controller:IController = null) { super(); this.model = model; if (controller != null) { this.controller = controller; } } /** @inheritDoc */ public function asDisplayObject():DisplayObject { return this; } /** @inheritDoc */ public function get model():* { return _model; } public function set model(model:*):void { _model = model; } protected var _model:*; + /** * The controller for the model that the view will use to modify it. * If it is set to null, the default controller will be used. */ public function get controller():IController { // If a controller hasn't been defined yet... if (_controller == null) { // ...make one. Note that defaultController() is normally overridden // by the AbstractView subclass so that it returns the appropriate // controller for the view. this.controller = getDefaultController( model ); this.controller.view = this; } return controller; } public function set controller(controller:IController):void { _controller = controller; controller.view = this; } protected var _controller:IController; public function getDefaultController( model:* ):IController { // AbstractEnforcer.enforceMethod(); return null; } } } \ No newline at end of file
as3/as3-utils
56a6035b71aef297cc885f1d686af6e4d8451704
added abstract model
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index 48847cb..1797641 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/mvc/AbstractModel.as b/src/utils/mvc/AbstractModel.as new file mode 100644 index 0000000..0178713 --- /dev/null +++ b/src/utils/mvc/AbstractModel.as @@ -0,0 +1,19 @@ +package utils.mvc +{ + import flash.events.EventDispatcher; + import flash.events.IEventDispatcher; + + /** + * Specifies the minimum functionality that the "model" of + * a Model/View/Controller triad must provide. + * + * @author Mims Wright + */ + public class AbstractModel extends EventDispatcher implements IModel + { + public function AbstractModel() + { + super(); + } + } +} \ No newline at end of file
as3/as3-utils
87128aac44bcbb6042f03e394e2d6d8897ef113b
added a model class
diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc index c254cbf..48847cb 100644 Binary files a/bin/as3-utils.swc and b/bin/as3-utils.swc differ diff --git a/src/utils/mvc/IModel.as b/src/utils/mvc/IModel.as new file mode 100644 index 0000000..8b14517 --- /dev/null +++ b/src/utils/mvc/IModel.as @@ -0,0 +1,15 @@ +package utils.mvc +{ + import flash.events.IEventDispatcher; + + /** + * Specifies the minimum functionality that the "model" of + * a Model/View/Controller triad must provide. + * + * @author Mims Wright + */ + public interface IModel extends IEventDispatcher + { + + } +} \ No newline at end of file
as3/as3-utils
430d57da8b2cab40fb654f9beb9a6a9ef9c2709d
ensure tests run and asdocs are generated
diff --git a/src/utils/align/alignCenter.as b/src/utils/align/alignCenter.as index 37cd7fa..d4dbee7 100644 --- a/src/utils/align/alignCenter.as +++ b/src/utils/align/alignCenter.as @@ -1,13 +1,11 @@ package utils.align { import flash.display.DisplayObject; - - /** * Center align object to target. */ public function alignCenter(item:DisplayObject, target:DisplayObject):void { xAlignCenter(item, target); yAlignCenter(item, target); } } diff --git a/src/utils/date/iso8601ToDate.as b/src/utils/date/iso8601ToDate.as index 285ebf9..3957295 100644 --- a/src/utils/date/iso8601ToDate.as +++ b/src/utils/date/iso8601ToDate.as @@ -1,71 +1,71 @@ package utils.date { import utils.conversion.minutesToHours; import utils.object.isEmpty; /** * Converts W3C ISO 8601 date String into a Date object. * Example code: * <pre> * trace(iso8601ToDate("1994-11-05T08:15:30-05:00").toString()); * </pre> * @param iso8601 Valid ISO 8601 formatted String * @return Date object of the specified date and time of the ISO 8601 String in universal time - * @see <a href="http://www.w3.org/TR/NOTE-datetime">W3C ISO 8601 specification</a> + * @see http://www.w3.org/TR/NOTE-datetime (W3C ISO 8601 specification) * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function iso8601ToDate(iso8601:String):Date { var parts:Array = iso8601.toUpperCase().split("T"); var date:Array = parts[0].split("-"); var time:Array = (parts.length <= 1) ? [] : parts[1].split(":"); var year:uint = isEmpty(date[0]) ? 0 : Number(date[0]); var month:uint = isEmpty(date[1]) ? 0 : Number(date[1] - 1); var day:uint = isEmpty(date[2]) ? 1 : Number(date[2]); var hour:int = isEmpty(time[0]) ? 0 : Number(time[0]); var minute:uint = isEmpty(time[1]) ? 0 : Number(time[1]); var second:uint = 0; var millisecond:uint = 0; if(time[2] != undefined) { var index:int = time[2].length; var temp:Number; if(time[2].indexOf("+") > -1) { index = time[2].indexOf("+"); } else if(time[2].indexOf("-") > -1) { index = time[2].indexOf("-"); } else if(time[2].indexOf("Z") > -1) { index = time[2].indexOf("Z"); } if(isNaN(index)) { temp = Number(time[2].slice(0, index)); second = Math.floor(temp); millisecond = 1000 * (temp % 1); } if(index != time[2].length) { var offset:String = time[2].slice(index); var userOffset:Number = minutesToHours(new Date(year, month, day).getTimezoneOffset()); switch(offset.charAt(0)) { case "+" : case "-" : hour -= userOffset + Number(offset.slice(0)); break; case "Z" : hour -= userOffset; break; default: } } } return new Date(year, month, day, hour, minute, second, millisecond); } } diff --git a/src/utils/date/timeCode.as b/src/utils/date/timeCode.as index 7feb77b..eb88010 100644 --- a/src/utils/date/timeCode.as +++ b/src/utils/date/timeCode.as @@ -1,18 +1,19 @@ package utils.date { - - /** * Utility function for generating time code given a number seconds. * @param sec Seconds * @return Timecode - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function timeCode(sec:Number):String { var h:Number = Math.floor(sec / 3600); var m:Number = Math.floor((sec % 3600) / 60); var s:Number = Math.floor((sec % 3600) % 60); - return (h == 0 ? "" : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + (m < 10 ? "0" + String(m) : String(m)) + ":" + (s < 10 ? "0" + String(s) : String(s)); + return (h == 0 ? "" + : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + + (m < 10 ? "0" + String(m) : String(m)) + ":" + + (s < 10 ? "0" + String(s) : String(s)); } } diff --git a/src/utils/display/cropBitmapData.as b/src/utils/display/cropBitmapData.as index 6457186..0d7d06a 100644 --- a/src/utils/display/cropBitmapData.as +++ b/src/utils/display/cropBitmapData.as @@ -1,23 +1,22 @@ package utils.display { + import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; - - /** * Crop the BitmapData source and return a new BitmapData. * @param source Source BitmapData * @param dest Crop area as Rectangle * @return Cropped source as BitmapData - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function cropBitmapData(source:BitmapData, dest:Rectangle):BitmapData { var o:BitmapData = new BitmapData(dest.width, dest.height); var point:Point = new Point(0, 0); o.copyPixels(source, dest, point); return o; } } diff --git a/src/utils/display/scheduleForNextFrame.as b/src/utils/display/scheduleForNextFrame.as index b6707f1..64ddc25 100644 --- a/src/utils/display/scheduleForNextFrame.as +++ b/src/utils/display/scheduleForNextFrame.as @@ -1,21 +1,20 @@ package utils.display { + import flash.display.Shape; import flash.events.Event; - - /** * Wait for a next frame. * Prevents high CPU state, when AVM doesn't send ENTER_FRAMES. It just simply waits until it gets one. * @param callback Function to call once when next frame is displayed - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function scheduleForNextFrame(callback:Function):void { var obj:Shape = new Shape(); obj.addEventListener(Event.ENTER_FRAME, function(ev:Event):void { obj.removeEventListener(Event.ENTER_FRAME, arguments.callee); callback(); }); } } diff --git a/src/utils/display/traceChildren.as b/src/utils/display/traceChildren.as index 3429be1..e5eeb63 100644 --- a/src/utils/display/traceChildren.as +++ b/src/utils/display/traceChildren.as @@ -1,27 +1,30 @@ package utils.display { + import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; - - /** * trace() children of the DisplayObjectContainer. * @param container DisplayObjectContainer to get children of * @param indentLevel Indentation level (default 0) - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function traceChildren(container:DisplayObjectContainer, indentLevel:int = 0):void { for(var i:int = 0; i < container.numChildren; i++) { var thisChild:DisplayObject = container.getChildAt(i); var output:String = ""; - for(var j:int = 0; j < indentLevel; j++) output += " "; + for(var j:int = 0; j < indentLevel; j++) { + output += " "; + } output += "+ " + thisChild.name + " = " + String(thisChild); trace(output); - if(thisChild is DisplayObjectContainer) traceChildren(DisplayObjectContainer(thisChild), indentLevel + 1); + if(thisChild is DisplayObjectContainer) { + traceChildren(DisplayObjectContainer(thisChild), indentLevel + 1); + } } } } diff --git a/src/utils/geom/simplifyAngle.as b/src/utils/geom/simplifyAngle.as index df9925b..c2008df 100644 --- a/src/utils/geom/simplifyAngle.as +++ b/src/utils/geom/simplifyAngle.as @@ -1,21 +1,19 @@ package utils.geom { - - /** * Simplifies the supplied angle to its simplest representation. * Example code: * <pre> * var simpAngle:Number = simplifyAngle(725); // returns 5 * var simpAngle2:Number = simplifyAngle(-725); // returns -5 * </pre> * @param angle Angle to simplify in degrees * @return Supplied angle simplified - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function simplifyAngle(angle:Number):Number { var _rotations:Number = Math.floor(angle / 360); return (angle >= 0) ? angle - (360 * _rotations) : angle + (360 * _rotations); } } diff --git a/src/utils/geom/trimAngle.as b/src/utils/geom/trimAngle.as index 5ace1aa..fabad9a 100644 --- a/src/utils/geom/trimAngle.as +++ b/src/utils/geom/trimAngle.as @@ -1,23 +1,21 @@ package utils.geom { - - /** * Trims the supplied angle to its 0..360 representation. * Example code: * <pre> * var simpAngle:Number = trimAngle(725); // returns 5 * </pre> * @param value Angle to trim * @return Supplied angle trimmed - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function trimAngle(value:Number):Number { var a:Number = value; while(a < 0) a += 360; while(a > 360) a -= 360; return a; } } diff --git a/src/utils/js/callJSFunction.as b/src/utils/js/callJSFunction.as index e527844..2cd5578 100644 --- a/src/utils/js/callJSFunction.as +++ b/src/utils/js/callJSFunction.as @@ -1,40 +1,38 @@ package utils.js { import flash.external.ExternalInterface; - - /** * Call a JS function. * @param func Name of the function to be called * @param arg1 Argument 1 * @param arg2 Argument 2 * @param arg3 Argument 3 * @param arg4 Argument 4 * @throws Error if empty function name supplied * @throws Error if SecurityError occurred * @throws Error if Error occurred - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function callJSFunction(func:String, arg1:* = null, arg2:* = null, arg3:* = null, arg4:* = null):void { if(func == "") { throw new Error("A valid function argument must be supplied"); } // track avea if a type is supplied if(ExternalInterface.available) { try { ExternalInterface.call(func, arg1, arg2, arg3, arg4); } catch(error:SecurityError) { throw new Error(func + " request failed. A SecurityError occurred: " + error.message + "\n"); } catch (error:Error) { throw new Error(func + " request failed. An Error occurred: " + error.message + "\n"); } } else { throw new Error(func + " request Failed. External interface is not available for this container. If you're trying to use it locally, try using it through an HTTP address."); } } } diff --git a/src/utils/location/getDomain.as b/src/utils/location/getDomain.as index 2e94847..69bf30e 100644 --- a/src/utils/location/getDomain.as +++ b/src/utils/location/getDomain.as @@ -1,24 +1,23 @@ package utils.location { + import flash.display.DisplayObject; - - /** * Detects MovieClip domain location. * Function does not return folder path or file name. The method also treats "www" and sans "www" as the same; if "www" is present method does not return it. * Example code: * <pre> * trace(getDomain(_root)); * </pre> * @param location MovieClip to get location of * @return Full domain (including sub-domains) of MovieClip location * @author Aaron Clinger * @author Shane McCartney * @author David Nelson - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function getDomain(location:DisplayObject):String { var baseUrl:String = location.loaderInfo.url.split("://")[1].split("/")[0]; return (baseUrl.substr(0, 4) == "www.") ? baseUrl.substr(4) : baseUrl; } } diff --git a/src/utils/location/getLocationName.as b/src/utils/location/getLocationName.as index 87e88bd..f71da2f 100644 --- a/src/utils/location/getLocationName.as +++ b/src/utils/location/getLocationName.as @@ -1,53 +1,52 @@ package utils.location { + import flash.external.ExternalInterface; import utils.capabilities.isStandAlone; - - /** * Return current location name. * @return Current location name * @author Aaron Clinger * @author Shane McCartney * @author David Nelson - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function getLocationName():String { var out:String; var browserAgent:String; if(isStandAlone()) { out = locationNames.STANDALONE_PLAYER; } else { if(ExternalInterface.available) { // uses external interface to reach out to browser and grab browser useragent info. browserAgent = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); // determines brand of browser using a find index. If not found indexOf returns (-1). // noinspection IfStatementWithTooManyBranchesJS if(browserAgent != null && browserAgent.indexOf("Firefox") >= 0) { out = locationNames.BROWSER_FIREFOX; } else if(browserAgent != null && browserAgent.indexOf("Safari") >= 0) { out = locationNames.BROWSER_SAFARI; } else if(browserAgent != null && browserAgent.indexOf("MSIE") >= 0) { out = locationNames.BROWSER_IE; } else if(browserAgent != null && browserAgent.indexOf("Opera") >= 0) { out = locationNames.BROWSER_OPERA; } else { out = locationNames.BROWSER_UNDEFINED; } } else { // standalone player out = locationNames.BROWSER_UNDEFINED; } } return out; } } diff --git a/src/utils/string/convertBytesString.as b/src/utils/string/convertBytesString.as index d936562..56ea3dd 100644 --- a/src/utils/string/convertBytesString.as +++ b/src/utils/string/convertBytesString.as @@ -1,15 +1,14 @@ package utils.string { + import utils.conversion.bytesToKilobytes; - - /** * Convert bytes to a String ("X B" or "X kB") * @param value Bytes count * @return Result String - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function convertBytesString(value:uint):String { return (value <= 8192 ? (String(value) + " B") : (String(bytesToKilobytes(value)) + " kB")); } } diff --git a/src/utils/string/randomSequence.as b/src/utils/string/randomSequence.as index 4276224..2ad0bc3 100644 --- a/src/utils/string/randomSequence.as +++ b/src/utils/string/randomSequence.as @@ -1,16 +1,15 @@ package utils.string { + import utils.number.randomIntegerWithinRange; - - /** * Get random sentence. * @param maxLength Max chars * @param minLength Min chars * @return Random sentence - * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function randomSequence(maxLength:uint = 50, minLength:uint = 10):String { return randomCharacters(randomIntegerWithinRange(minLength, maxLength), " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); } } diff --git a/src/utils/validation/US_STATE_ABBREVIATIONS.as b/src/utils/validation/US_STATE_ABBREVIATIONS.as index ebc9777..b57e85f 100644 --- a/src/utils/validation/US_STATE_ABBREVIATIONS.as +++ b/src/utils/validation/US_STATE_ABBREVIATIONS.as @@ -1,5 +1,10 @@ package utils.validation { - public const US_STATE_ABBREVIATIONS:Array = ['ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', - 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy']; + public const US_STATE_ABBREVIATIONS:Array = [ + 'ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', + 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', + 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', 'nd', + 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', + 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', + 'wy']; } \ No newline at end of file diff --git a/src/utils/xml/getSiblingByIndex.as b/src/utils/xml/getSiblingByIndex.as index ac55fbd..6e7c76b 100644 --- a/src/utils/xml/getSiblingByIndex.as +++ b/src/utils/xml/getSiblingByIndex.as @@ -1,44 +1,43 @@ package utils.xml { /** * Returns the sibling at the index specified relative to the node's parent. * * @param x The node whose sibling will be returned. * * @return The sibling of the node at the specified position. null if the node does not have * a sibling at that position, or if the node has no parent. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * * @example Getting a sibling 2 positions behind a node - * <listing version="3.0" > - * var x:XML = - * <root> + * <listing version="3.0"> + * var x:XML = <root> * <stuff>value1</stuff> * <stuff>value2</stuff> * <stuff>value3</stuff> * </root>; * - * //Request sibling 2 positions before "value3" - * var sibling:XML = getSiblingByIndex(x.stuff[2], -2); + * //Request sibling 2 positions before "value3" + * var sibling:XML = getSiblingByIndex(x.stuff[2], -2); * - * //returns "value1" - *</listing> + * //returns "value1" + * </listing> */ public function getSiblingByIndex(x:XML, count:int):XML { var out:XML; try { out = x.parent().children()[x.childIndex() + count]; } catch (e:Error) { return null; } return out; } } \ No newline at end of file diff --git a/test/UtilsTestRunner.as b/test/UtilsTestRunner.as new file mode 100644 index 0000000..a30ff58 --- /dev/null +++ b/test/UtilsTestRunner.as @@ -0,0 +1,30 @@ +package +{ + import flash.display.Sprite; + + import org.flexunit.internals.TraceListener; + import org.flexunit.listeners.CIListener; + import org.flexunit.runner.FlexUnitCore; + import org.fluint.uiImpersonation.IVisualTestEnvironment; + import org.fluint.uiImpersonation.VisualTestEnvironmentBuilder; + + public class UtilsTestRunner extends Sprite + { + private var core:FlexUnitCore; + private var env:IVisualTestEnvironment; + + public function UtilsTestRunner() + { + super(); + + // make the stage available to tests + env = VisualTestEnvironmentBuilder.getInstance(this).buildVisualTestEnvironment(); + + // run + core = new FlexUnitCore(); + core.addListener(new TraceListener()); + core.addListener(new CIListener()); + core.run( UtilsTestSuite ); + } + } +} \ No newline at end of file diff --git a/test/UtilsTestSuite.as b/test/UtilsTestSuite.as new file mode 100644 index 0000000..c6d9dc5 --- /dev/null +++ b/test/UtilsTestSuite.as @@ -0,0 +1,114 @@ +package +{ + import org.flexunit.runners.Suite; + + import utils.align.AlignCenterTest; + import utils.align.AlignLeftTest; + import utils.align.AlignRightTest; + import utils.date.GetNextDayTest; + import utils.date.GetPrevDayTest; + import utils.date.GetTimeElapsedStringTest; + import utils.date.calendar.CalendarTests; + import utils.dictionary.CircularDictionaryTest; + import utils.geom.CartesianToPolarCoordinatesTest; + import utils.geom.PolarToCartesianCoordinatesTest; + import utils.number.ClampTest; + import utils.number.ToHexTest; + import utils.object.CloneTest; + import utils.object.ContainsTest; + import utils.object.CreateInstanceTest; + import utils.object.CreateTest; + import utils.object.MergeTest; + import utils.range.RandomRangeDateTest; + import utils.string.NumberToStringTest; + import utils.string.StringHasValueTest; + import utils.type.IsPassedByValueTest; + import utils.type.StrictIsTest; + import utils.validation.EncodeCreditCardNumberTest; + import utils.validation.GetCreditCardProviderTest; + import utils.validation.IsBlankTest; + import utils.validation.IsCreditCardTest; + import utils.validation.IsEmailTest; + import utils.validation.IsNumericTest; + import utils.validation.IsPOBoxTest; + import utils.validation.IsUSAStateAbbreviationTest; + import utils.validation.IsUrlTest; + import utils.validation.IsValidCreditCardNumberTest; + import utils.validation.IsValidEmailAddressTest; + import utils.validation.IsValidExpirationDateTest; + import utils.validation.IsValidPhoneNumberTest; + import utils.xml.GetNextSiblingTest; + import utils.xml.GetPreviousSiblingTest; + import utils.xml.GetSiblingByIndexTest; + import utils.xml.IsValidXMLTest; + + Suite; + + [RunWith("org.flexunit.runners.Suite")] + [Suite] + public class UtilsTestSuite + { + // utils.align + public var alignCenterTest:AlignCenterTest; + public var alignLeftTest:AlignLeftTest; + public var alighRightTest:AlignRightTest; + + // utils.date.calendar + public var calendarTest:CalendarTests; + + // utils.date + public var getNextDayTest:GetNextDayTest; + public var getPrevDayTest:GetPrevDayTest; + public var getTimeElapsedStringTest:GetTimeElapsedStringTest; + + // utils.dictionary + public var circularDictionaryTest:CircularDictionaryTest; + + // utils.geom + public var cartesianToPolarCoordinatesTest:CartesianToPolarCoordinatesTest; + public var polarToCartesianCoordinatesTest:PolarToCartesianCoordinatesTest; + + // utils.number + public var clampTest:ClampTest; + public var toHexTest:ToHexTest; + + // utils.object + public var cloneTest:CloneTest; + public var containsTest:ContainsTest; + public var createInstanceTest:CreateInstanceTest; + public var createTest:CreateTest; + public var mergeTest:MergeTest; + + // utils.range + public var randomRangeDateTest:RandomRangeDateTest; + + // utils.string + public var numberToStringTest:NumberToStringTest; + public var stringHasValueTest:StringHasValueTest; + + // utils.type + public var isPassedByValueTest:IsPassedByValueTest; + public var strictIsTest:StrictIsTest; + + // utils.validation +// public var encodeCreditCardNumberTest:EncodeCreditCardNumberTest; +// public var getCreditCardProviderTest:GetCreditCardProviderTest; +// public var isBlankTest:IsBlankTest; +// public var isCreditCardTest:IsCreditCardTest; +// public var isEmailTest:IsEmailTest; +// public var isNumericTest:IsNumericTest; +// public var isPOBoxTest:IsPOBoxTest; +// public var isUrlTest:IsUrlTest; +// public var isUSAStateAbbreviation:IsUSAStateAbbreviationTest; + public var isValidCreditCardNumberTest:IsValidCreditCardNumberTest; + public var isValidEmailAddress:IsValidEmailAddressTest; + public var isValidExpirationDate:IsValidExpirationDateTest; + public var isValidPhoneNumberTest:IsValidPhoneNumberTest; + + // utils.xml + public var getNextSiblingTest:GetNextSiblingTest; + public var getPreviousSiblingTest:GetPreviousSiblingTest; + public var getSiblingByIndexTest:GetSiblingByIndexTest; + public var isValidXMLTest:IsValidXMLTest; + } +} \ No newline at end of file diff --git a/test/utils/align/alignCenterTest.as b/test/utils/align/alignCenterTest.as index 2b3da96..5b3bdf6 100644 --- a/test/utils/align/alignCenterTest.as +++ b/test/utils/align/alignCenterTest.as @@ -1,61 +1,57 @@ package utils.align { import flash.display.Sprite; - - import mx.core.UIComponent; - + import org.fluint.uiImpersonation.UIImpersonator; import org.hamcrest.assertThat; - import org.hamcrest.object.equalTo; - public class alignCenterTest + public class AlignCenterTest { [Test] public function alignCenter_aligns_display_object_centers_x():void { var item:Sprite = drawSprite(10,10,10,10); var target:Sprite = drawSprite(20,20,10,10); addItemAndTargetToStage(item, target); alignCenter(item, target); assertThat(item.x, equalTo(target.x)); } [Test] public function alignCenter_aligns_display_object_centers_y():void { var item:Sprite = drawSprite(10,10,10,10); var target:Sprite = drawSprite(20,20,10,10); addItemAndTargetToStage(item, target); alignCenter(item, target); assertThat(item.y, equalTo(target.y)); } private function drawSprite(x:int, y:int, width:int, height:int):Sprite { var sprite:Sprite = new Sprite(); sprite.graphics.beginFill(0x000000); sprite.graphics.drawRect(0,0,width,height); sprite.x = x; sprite.y = y; return sprite; } private function addItemAndTargetToStage(item:Sprite, target:Sprite):void { - var uiComponent:UIComponent = new UIComponent(); - - UIImpersonator.addChild(uiComponent); - uiComponent.addChild(item); - uiComponent.addChild(target); + var container:Sprite = new Sprite(); + container.addChild(item); + container.addChild(target); + UIImpersonator.addChild(container); } } } \ No newline at end of file diff --git a/test/utils/object/cloneTest.as b/test/utils/object/cloneTest.as index 4d312eb..e54f7da 100644 --- a/test/utils/object/cloneTest.as +++ b/test/utils/object/cloneTest.as @@ -1,31 +1,31 @@ package utils.object { import org.hamcrest.assertThat; import org.hamcrest.object.hasProperties; - public class cloneTest + public class CloneTest { [Test] public function clone_creates_object_with_equal_properties():void { var originalObject:SimpleObject = new SimpleObject(); var cloneObject:Object; cloneObject = clone(originalObject); assertThat( "cloned object properties equal original object properties", cloneObject, hasProperties({propOne:"propOne",propTwo:true,propThree:10}) ); } } } class SimpleObject { public var propOne:String = "propOne"; public var propTwo:Boolean = true; public var propThree:int = 10; } \ No newline at end of file diff --git a/test/utils/object/containsTest.as b/test/utils/object/containsTest.as index eeb23b6..1cc1d95 100644 --- a/test/utils/object/containsTest.as +++ b/test/utils/object/containsTest.as @@ -1,19 +1,19 @@ package utils.object { import flexunit.framework.Assert; import utils.object.contains; - public class containsTest + public class ContainsTest { [Test] public function testContains():void { var o:Object = {foo:"bar", baz:42}; var p:Object = {foo:o}; Assert.assertTrue("Object contains 'bar'", contains(o, "bar")); Assert.assertFalse("Doesn't check property names", contains(o, "foo")); Assert.assertTrue("Object contains other objects", contains(p, o)); } } } \ No newline at end of file diff --git a/test/utils/string/numberToStringTest.as b/test/utils/string/numberToStringTest.as index 1546429..600ce67 100644 --- a/test/utils/string/numberToStringTest.as +++ b/test/utils/string/numberToStringTest.as @@ -1,43 +1,43 @@ package utils.string { import org.flexunit.asserts.*; - public class numberToStringTest + public class NumberToStringTest { [Before] public function setup():void { } [Test] public function numberToStringTestPositiveNumbers():void { assertEquals("eleven", numberToString(11)); assertEquals("ten thousand", numberToString(10000)); assertEquals("one billion two hundred thirty four million five hundred sixty seven thousand eight hundred ninety", numberToString(1234567890)); } [Test] public function numberToStringTestDecimalNumbers():void { assertEquals("point one two three four five", numberToString(0.12345)); assertEquals("one hundred one point zero zero one", numberToString(101.001)); } [Test] public function numberToStringTestNegativeNumbers():void { assertEquals("negative one", numberToString(-1)); } [Test] public function numberToStringTestZero():void { assertEquals("zero", numberToString(0)); } [Test] public function numberToStringTestNaN():void { assertEquals("not a number", numberToString(NaN)); assertEquals("not a number", numberToString(undefined)); } } } \ No newline at end of file diff --git a/test/utils/string/stringHasValueTest.as b/test/utils/string/stringHasValueTest.as index 14fac6b..3ddc9c2 100644 --- a/test/utils/string/stringHasValueTest.as +++ b/test/utils/string/stringHasValueTest.as @@ -1,51 +1,51 @@ package utils.string { import org.hamcrest.assertThat; import org.hamcrest.object.isFalse; import org.hamcrest.object.isTrue; - public class stringHasValueTest + public class StringHasValueTest { [Test] public function stringHasValue_is_true_for_a_string_with_a_value():void { var stringDoesHaveValue:Boolean; stringDoesHaveValue = stringHasValue("someString"); assertThat( "The string has a value.", stringDoesHaveValue, isTrue() ); } [Test] public function stringHasValue_is_false_for_a_string_with_no_value():void { var noCharStringHasValue:Boolean; noCharStringHasValue = stringHasValue(""); assertThat( "The string has no value.", noCharStringHasValue, isFalse() ); } [Test] public function stringHasValue_is_false_for_null():void { var nullHasValueAsString:Boolean; nullHasValueAsString = stringHasValue(null); assertThat( "Null has no value.", nullHasValueAsString, isFalse() ); } } } \ No newline at end of file diff --git a/test/utils/validation/isValidEmailAddress.as b/test/utils/validation/IsValidEmailAddressTest.as similarity index 52% rename from test/utils/validation/isValidEmailAddress.as rename to test/utils/validation/IsValidEmailAddressTest.as index 13f2fe5..31af131 100644 --- a/test/utils/validation/isValidEmailAddress.as +++ b/test/utils/validation/IsValidEmailAddressTest.as @@ -1,43 +1,43 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:47 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; -import utils.validation.isValidEmailAddress; +import utils.validation.IsValidEmailAddressTest; -public class isValidEmailAddress { +public class IsValidEmailAddressTest { [Test] public function goodEmailPasses() : void { - assertThat(utils.validation.isValidEmailAddress("[email protected]"), equalTo(true)) + assertThat(isValidEmailAddress("[email protected]"), equalTo(true)) } [Test] public function emailWithSpaceFails() : void { - assertThat(utils.validation.isValidEmailAddress("test@ test.com"), equalTo(false)) + assertThat(isValidEmailAddress("test@ test.com"), equalTo(false)) } [Test] public function emailWithoutAtSymbolFails() : void { - assertThat(utils.validation.isValidEmailAddress("testtest.com"), equalTo(false)) + assertThat(isValidEmailAddress("testtest.com"), equalTo(false)) } [Test] public function emailWithInvalidCharacterFails() : void { - assertThat(utils.validation.isValidEmailAddress("test@te$t.com"), equalTo(false)) + assertThat(isValidEmailAddress("test@te$t.com"), equalTo(false)) } } } diff --git a/test/utils/validation/encodeCreditCardNumberTest.as b/test/utils/validation/encodeCreditCardNumberTest.as index 546858f..ca4f64f 100644 --- a/test/utils/validation/encodeCreditCardNumberTest.as +++ b/test/utils/validation/encodeCreditCardNumberTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 3:07 PM */ package utils.validation { -public class encodeCreditCardNumberTest { - public function encodeCreditCardNumberTest() { +public class EncodeCreditCardNumberTest { + public function EncodeCreditCardNumberTest() { } } } diff --git a/test/utils/validation/getCreditCardProviderTest.as b/test/utils/validation/getCreditCardProviderTest.as index c8fad39..6ee3220 100644 --- a/test/utils/validation/getCreditCardProviderTest.as +++ b/test/utils/validation/getCreditCardProviderTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 1:26 PM */ package utils.validation { -public class getCreditCardProviderTest { - public function getCreditCardProviderTest() { +public class GetCreditCardProviderTest { + public function GetCreditCardProviderTest() { } } } diff --git a/test/utils/validation/isBlankTest.as b/test/utils/validation/isBlankTest.as index 4847299..0cc6e43 100644 --- a/test/utils/validation/isBlankTest.as +++ b/test/utils/validation/isBlankTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:48 AM */ package utils.validation { -public class isBlankTest { - public function isBlankTest() { +public class IsBlankTest { + public function IsBlankTest() { } } } diff --git a/test/utils/validation/isCreditCardTest.as b/test/utils/validation/isCreditCardTest.as index 5365602..ab42edc 100644 --- a/test/utils/validation/isCreditCardTest.as +++ b/test/utils/validation/isCreditCardTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:44 AM */ package utils.validation { -public class isCreditCardTest { - public function isCreditCardTest() { +public class IsCreditCardTest { + public function IsCreditCardTest() { } } } diff --git a/test/utils/validation/isEmailTest.as b/test/utils/validation/isEmailTest.as index 9590865..7c38e33 100644 --- a/test/utils/validation/isEmailTest.as +++ b/test/utils/validation/isEmailTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:39 AM */ package utils.validation { -public class isEmailTest { - public function isEmailTest() { +public class IsEmailTest { + public function IsEmailTest() { } } } diff --git a/test/utils/validation/isNumericTest.as b/test/utils/validation/isNumericTest.as index 2a4e80a..7f677b0 100644 --- a/test/utils/validation/isNumericTest.as +++ b/test/utils/validation/isNumericTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:37 AM */ package utils.validation { -public class isNumericTest { - public function isNumericTest() { +public class IsNumericTest { + public function IsNumericTest() { } } } diff --git a/test/utils/validation/isPOBoxTest.as b/test/utils/validation/isPOBoxTest.as index e16ccf6..9b6d442 100644 --- a/test/utils/validation/isPOBoxTest.as +++ b/test/utils/validation/isPOBoxTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:35 AM */ package utils.validation { -public class isPOBoxTest { - public function isPOBoxTest() { +public class IsPOBoxTest { + public function IsPOBoxTest() { } } } diff --git a/test/utils/validation/isUSAStateAbbreviationTest.as b/test/utils/validation/isUSAStateAbbreviationTest.as index 3e01f0b..afa2231 100644 --- a/test/utils/validation/isUSAStateAbbreviationTest.as +++ b/test/utils/validation/isUSAStateAbbreviationTest.as @@ -1,27 +1,24 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:24 AM */ package utils.validation { import org.flexunit.asserts.fail; -import org.flexunit.flexui.patterns.AssertThatPattern; -import org.hamcrest.assertThat; -import org.hamcrest.object.equalTo; -public class isUSAStateAbbreviationTest { +public class IsUSAStateAbbreviationTest { [Test] - public function isUSAStateAbbreviationTest() { + public function IsUSAStateAbbreviationTest() { new Array('ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy'); // assertThat(isUSAStateAbbreviation("DE"), // equalTo()) fail("test remains to be implemented") } } } diff --git a/test/utils/validation/isUrlTest.as b/test/utils/validation/isUrlTest.as index 06adbf4..386a085 100644 --- a/test/utils/validation/isUrlTest.as +++ b/test/utils/validation/isUrlTest.as @@ -1,12 +1,12 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:29 AM */ package utils.validation { -public class isUrlTest { - public function isUrlTest() { +public class IsUrlTest { + public function IsUrlTest() { } } } diff --git a/test/utils/validation/isValidCreditCardNumberTest.as b/test/utils/validation/isValidCreditCardNumberTest.as index 7f76bc4..4eba1f5 100644 --- a/test/utils/validation/isValidCreditCardNumberTest.as +++ b/test/utils/validation/isValidCreditCardNumberTest.as @@ -1,70 +1,70 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:52 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidCreditCardNumber; -public class isValidCreditCardNumberTest { +public class IsValidCreditCardNumberTest { [Test] public function ccBelowMinimum13ShouldFail() : void { assertThat(isValidCreditCardNumber("1234"), equalTo(false)); } [Test] public function ccAboveMaximum16ShouldFail() : void { assertThat(isValidCreditCardNumber("123413123123213421341123412423412412341232314"), equalTo(false)); } //Even CC length integrity testing //Each number is examined //if a number is divisible by 2 with no remainder (even) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. //if a number is divisible by 2 with a remainder (odd) it gets added to the second group //The first group plus the second group should be divisible by 10 with no remainder [Test] public function ccEvenNumberLengthWithBadIntegrityShouldFail() : void { assertThat(isValidCreditCardNumber("12345678901234"), equalTo(false)); } [Test] public function ccEvenNumberLengthWithGoodIntegrityShouldPass() : void { assertThat(isValidCreditCardNumber("72345678901234"), equalTo(true)); } //Odd CC length integrity testing //Each number is examined //if a number is divisible by 1 with no remainder (odd) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. //if a number is divisible by 1 with a remainder (even) it gets added to the second group //The first group plus the second group should be divisible by 10 with no remainder [Test] public function ccOddNumberLengthWithBadIntegrityShouldFail() : void { assertThat(isValidCreditCardNumber("123456789012345"), equalTo(false)); } [Test] public function ccOddNumberLengthWithGoodIntegrityShouldPass() : void { assertThat(isValidCreditCardNumber("323456789012345"), equalTo(true)); } } } diff --git a/test/utils/validation/isValidExpirationDateTest.as b/test/utils/validation/isValidExpirationDateTest.as index 950a00c..ca0d920 100644 --- a/test/utils/validation/isValidExpirationDateTest.as +++ b/test/utils/validation/isValidExpirationDateTest.as @@ -1,51 +1,51 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:34 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidExpirationDate; -public class isValidExpirationDateTest { +public class IsValidExpirationDateTest { [Test] public function expirationOfNextYearShouldPass() : void { assertThat(isValidExpirationDate(1, new Date().getFullYear() + 1), equalTo(true)); } [Test] public function expirationOfLastYearShouldFail() : void { assertThat(isValidExpirationDate(1, new Date().getFullYear() - 1), equalTo(false)); } [Test] public function expirationOfSameYearButUpcomingMonthShouldPass() : void { assertThat(isValidExpirationDate(new Date().getMonth() + 1, new Date().getFullYear()), equalTo(true)); } [Test] public function expirationOfSameYearButPastMonthShouldFail() : void { assertThat(isValidExpirationDate(new Date().getMonth() - 1, new Date().getFullYear()), equalTo(false)); } [Test] public function expirationOfUpcomingYearWithMonthOfZeroShouldFail() : void { assertThat(isValidExpirationDate(0,new Date().getFullYear() + 1), equalTo(true)); } } } diff --git a/test/utils/validation/isValidPhoneNumberTest.as b/test/utils/validation/isValidPhoneNumberTest.as index 27cb87b..28ed5a7 100644 --- a/test/utils/validation/isValidPhoneNumberTest.as +++ b/test/utils/validation/isValidPhoneNumberTest.as @@ -1,40 +1,40 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 5:32 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidPhoneNumber; -public class isValidPhoneNumberTest { +public class IsValidPhoneNumberTest { [Test] public function validNumberPasses() : void { assertThat(isValidPhoneNumber("123 456-7789"), equalTo(true)); } [Test] public function validNumberNoDashesPasses() : void { assertThat(isValidPhoneNumber("123 456 7789"), equalTo(true)); } //TODO: Should this be the intended behavior? [Test] public function validNumberWithPrefixFails() : void { assertThat(isValidPhoneNumber("1 123 456-7789"), equalTo(false)); } } } diff --git a/test/utils/xml/isValidXMLTest.as b/test/utils/xml/isValidXMLTest.as index c074dfa..0390cc1 100644 --- a/test/utils/xml/isValidXMLTest.as +++ b/test/utils/xml/isValidXMLTest.as @@ -1,32 +1,32 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/2/11 * Time: 4:40 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; -public class isValidXMLTest { +public class IsValidXMLTest { [Test] public function validXMLShouldReturnTrue() : void { var s:String = "<goodxml></goodxml>"; assertThat(isValidXML(s), equalTo(true)) } [Test] public function invalidXMLShouldReturnFalse() : void { var s:String = "<badXml></badXmL>"; assertThat(isValidXML(s), equalTo(false)) } } }
as3/as3-utils
156b5eb4aa1ba0f76e2df5be75b7967be06401d6
ignore FlashBuilder generated FlexUnit classes
diff --git a/.gitignore b/.gitignore index 94217da..ad1fa74 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,15 @@ +src/FlexUnitApplication.mxml +src/FlexUnitCompilerApplication.mxml target +bin/FlexUnitApplication.swf bin-debug bin-release *.iml .actionScript* .flex* .Flex* .project .settings/ .DS_Store launch org.eclipse.core.resources.prefs \ No newline at end of file
as3/as3-utils
704113aff4bad4e7cd93d7d96c56cda21ac8cff4
added binary to the repo
diff --git a/.gitignore b/.gitignore index d93f0b5..94217da 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,12 @@ target -bin bin-debug bin-release *.iml .actionScript* .flex* .Flex* .project .settings/ .DS_Store launch org.eclipse.core.resources.prefs \ No newline at end of file diff --git a/bin/as3-utils.swc b/bin/as3-utils.swc new file mode 100644 index 0000000..dddab51 Binary files /dev/null and b/bin/as3-utils.swc differ
as3/as3-utils
51db602874053ee589abaf6c13dd2742df7311fe
tweaked duplicatedisplayobject
diff --git a/src/utils/display/duplicateDisplayObject.as b/src/utils/display/duplicateDisplayObject.as index 0f6c653..7222d56 100644 --- a/src/utils/display/duplicateDisplayObject.as +++ b/src/utils/display/duplicateDisplayObject.as @@ -1,57 +1,57 @@ package utils.display { import flash.display.DisplayObject; import flash.display.Graphics; import flash.geom.Rectangle; import flash.system.Capabilities; /** * duplicateDisplayObject * creates a duplicate of the DisplayObject passed. * similar to duplicateMovieClip in AVM1. If using Flash 9, make sure * you export for ActionScript the symbol you are duplicating * * @param source the display object to duplicate * @param autoAdd if true, adds the duplicate to the display list * in which source was located * @return a duplicate instance of source * * @author Trevor McCauley - www.senocular.com * @author cleaned up by Mims Wright */ public function duplicateDisplayObject(source:DisplayObject, autoAdd:Boolean = false):DisplayObject { - var sourceClass:Class = Class(source.constructor); + var sourceClass:Class = Class(Object(source).constructor); var duplicate:DisplayObject = new sourceClass() as DisplayObject; // duplicate properties duplicate.transform = source.transform; duplicate.filters = source.filters; duplicate.cacheAsBitmap = source.cacheAsBitmap; duplicate.opaqueBackground = source.opaqueBackground; if(source.scale9Grid) { var rect:Rectangle = source.scale9Grid; // version check for scale9Grid bug if(Capabilities.version.split(" ")[1] == "9,0,16,0") { // Flash 9 bug where returned scale9Grid as twips rect.x /= 20,rect.y /= 20,rect.width /= 20,rect.height /= 20; } duplicate.scale9Grid = rect; } // todo: needs test if("graphics" in source) { var graphics:Graphics = Graphics(source["graphics"]); Graphics(duplicate["graphics"]).copyFrom(graphics); } // add to target parent's display list // if autoAdd was provided as true if(autoAdd && source.parent) { source.parent.addChild(duplicate); } return duplicate; } }
as3/as3-utils
66e6007412d32966608b724cbae5e3b680fb4d32
Reduced number of warnings in FDT. added launch folder to list of ignored files.
diff --git a/.gitignore b/.gitignore index 5a2139e..d93f0b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,13 @@ target bin bin-debug bin-release *.iml .actionScript* .flex* .Flex* .project .settings/ .DS_Store +launch org.eclipse.core.resources.prefs \ No newline at end of file diff --git a/src/utils/array/randomize.as b/src/utils/array/randomize.as index f22793d..80ab3aa 100644 --- a/src/utils/array/randomize.as +++ b/src/utils/array/randomize.as @@ -1,32 +1,32 @@ package utils.array { import utils.number.randomIntegerWithinRange; /** Creates new Array composed of passed Array's items in a random order. @param inArray: Array to create copy of, and randomize. @return A new Array composed of passed Array's items in a random order. @example <code> var numberArray:Array = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); trace(ArrayUtil.randomize(numberArray)); </code> */ public function randomize(inArray:Array):Array { var t:Array = new Array(); var r:Array = inArray.sort( function(a:*, b:*):int { - return randomIntegerWithinRange(0, 1) ? 1 : -1 + return randomIntegerWithinRange(0, 1) ? 1 : -1; } , Array.RETURNINDEXEDARRAY); var i:int = -1; while (++i < inArray.length) t.push(inArray[r[i]]); return t; } } \ No newline at end of file diff --git a/src/utils/date/makeMorning.as b/src/utils/date/makeMorning.as index 707242a..c78e474 100644 --- a/src/utils/date/makeMorning.as +++ b/src/utils/date/makeMorning.as @@ -1,15 +1,15 @@ package utils.date { /** * Converts a date into just after midnight. */ public function makeMorning(d:Date):Date { - var d:Date = new Date(d.time); + d = new Date(d.time); d.hours = 0; d.minutes = 0; d.seconds = 0; d.milliseconds = 0; return d; } } \ No newline at end of file diff --git a/src/utils/date/makeNight.as b/src/utils/date/makeNight.as index ccb802d..50b1c59 100644 --- a/src/utils/date/makeNight.as +++ b/src/utils/date/makeNight.as @@ -1,16 +1,16 @@ package utils.date { /** * Converts a date into just before midnight. */ public function makeNight(d:Date):Date { - var d:Date = new Date(d.time); + d = new Date(d.time); d.hours = 23; d.minutes = 59; d.seconds = 59; d.milliseconds = 999; return d; } } diff --git a/src/utils/display/addChild.as b/src/utils/display/addChild.as index a440833..d1fb28c 100644 --- a/src/utils/display/addChild.as +++ b/src/utils/display/addChild.as @@ -1,30 +1,30 @@ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * Allows you to add a child without first checking that the child or parent exist. * Allows you to add a child at an index higher than the number of children without error. * Allows you to use the same function for addChild and addChildAt. * * @param child The child DisplayObject to add. * @param parent The container to add the child to. * @param atIndex The index to add the child at. Default is to add to the top (-1) * @return Boolean True if the child was added, false if something prevented it from being added. * * @author Mims Wright */ public function addChild(child:DisplayObject, parent:DisplayObjectContainer, atIndex:int = -1):Boolean { if (child && parent) { if (atIndex < 0 || atIndex > parent.numChildren) { atIndex = parent.numChildren; } parent.addChildAt(child, atIndex); return true; } - return false + return false; } } \ No newline at end of file diff --git a/src/utils/display/bringToFront.as b/src/utils/display/bringToFront.as index f368901..f0a2648 100644 --- a/src/utils/display/bringToFront.as +++ b/src/utils/display/bringToFront.as @@ -1,25 +1,25 @@ package utils.display { import flash.display.DisplayObject; - import utils.number.clamp + import utils.number.clamp; /** * Brings the DisplayObject to the front of the display list. The <code>back</code> parameter can be used to pull the DisplayObject back a few levels from the front. * @param object the DisplayObject to reorder * @param back the number of levels from the front of the display list * @return the new index of the DisplayObject */ public function bringToFront(object:DisplayObject, back:uint = 0):int { if (!object.parent) return -1; var index:int = object.parent.numChildren - (back + 1); index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } \ No newline at end of file diff --git a/src/utils/display/duplicateDisplayObject.as b/src/utils/display/duplicateDisplayObject.as index 53a9e68..0f6c653 100644 --- a/src/utils/display/duplicateDisplayObject.as +++ b/src/utils/display/duplicateDisplayObject.as @@ -1,57 +1,57 @@ package utils.display { import flash.display.DisplayObject; import flash.display.Graphics; import flash.geom.Rectangle; import flash.system.Capabilities; /** * duplicateDisplayObject * creates a duplicate of the DisplayObject passed. * similar to duplicateMovieClip in AVM1. If using Flash 9, make sure * you export for ActionScript the symbol you are duplicating * * @param source the display object to duplicate * @param autoAdd if true, adds the duplicate to the display list * in which source was located * @return a duplicate instance of source * * @author Trevor McCauley - www.senocular.com * @author cleaned up by Mims Wright */ public function duplicateDisplayObject(source:DisplayObject, autoAdd:Boolean = false):DisplayObject { - var sourceClass:Class = Object(source).constructor; + var sourceClass:Class = Class(source.constructor); var duplicate:DisplayObject = new sourceClass() as DisplayObject; // duplicate properties duplicate.transform = source.transform; duplicate.filters = source.filters; duplicate.cacheAsBitmap = source.cacheAsBitmap; duplicate.opaqueBackground = source.opaqueBackground; if(source.scale9Grid) { var rect:Rectangle = source.scale9Grid; // version check for scale9Grid bug if(Capabilities.version.split(" ")[1] == "9,0,16,0") { // Flash 9 bug where returned scale9Grid as twips rect.x /= 20,rect.y /= 20,rect.width /= 20,rect.height /= 20; } duplicate.scale9Grid = rect; } // todo: needs test if("graphics" in source) { var graphics:Graphics = Graphics(source["graphics"]); Graphics(duplicate["graphics"]).copyFrom(graphics); } // add to target parent's display list // if autoAdd was provided as true if(autoAdd && source.parent) { source.parent.addChild(duplicate); } return duplicate; } } diff --git a/src/utils/display/removeChildAt.as b/src/utils/display/removeChildAt.as index 699fc8e..8136fd2 100644 --- a/src/utils/display/removeChildAt.as +++ b/src/utils/display/removeChildAt.as @@ -1,26 +1,25 @@ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; - import flash.filters.DisplacementMapFilter; /** * Removes the child at the index specified in a container and returns it. * Automatically handles cases that could potentially throw errors such as the index * being out of bounds or the parent being null. * * @param parent The container to remove the child from. * @param index The index to remove. If left blank or if out of bounds, defaults to the top child. * @return DisplayObject The child that was removed. * * @author Mims Wright */ public function removeChildAt(parent:DisplayObjectContainer, index:int = -1):DisplayObject { if (parent && parent.numChildren > 0) { if (index < 0 || index > parent.numChildren) { index = parent.numChildren; } var child:DisplayObject = parent.removeChildAt(index); } return null; } } \ No newline at end of file diff --git a/src/utils/geom/polarToCartesianCoordinates.as b/src/utils/geom/polarToCartesianCoordinates.as index 99b34e9..d468f61 100644 --- a/src/utils/geom/polarToCartesianCoordinates.as +++ b/src/utils/geom/polarToCartesianCoordinates.as @@ -1,26 +1,26 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 1:00:51 PM */ package utils.geom { import flash.geom.Point; /** * Converts polar coordinates to cartesian coordinates. * @param r The r value of the polar coordinate. * @param q The q value of the polar coordinate in degrees. */ public function polarToCartesianCoordinates(r:Number, q:Number) : Point { - var asRadian:Number = q * Math.PI/180 + var asRadian:Number = q * Math.PI/180; var x:Number = r * Math.cos(asRadian); var y:Number = r * Math.sin(asRadian); - return new Point(x,y) + return new Point(x,y); } } \ No newline at end of file diff --git a/src/utils/location/openURL.as b/src/utils/location/openURL.as index edda01b..c4f462f 100644 --- a/src/utils/location/openURL.as +++ b/src/utils/location/openURL.as @@ -1,36 +1,36 @@ package utils.location { import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; import utils.capabilities.isIDE; /** * Simlifies navigateToURL by allowing you to either use a String or an URLRequest * reference to the URL. This method also helps prevent pop-up blocking by trying to use * openWindow() before calling navigateToURL. * @param request A String or an URLRequest reference to the URL you wish to open/navigate to * @param window Browser window or HTML frame in which to display the URL indicated by the request parameter * @throws Error if you pass a value type other than a String or URLRequest to parameter request. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function openURL(request:*, window:String = "_self" /* windowNames.WINDOW_SELF */):void { var r:* = request; if(r is String) { r = new URLRequest(r); } else if(!(r is URLRequest)) { throw new Error("request"); } if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE() && request._data == null) { - if(openWindow(r.url, window)) return + if(openWindow(r.url, window)) return; } navigateToURL(r, window); } } diff --git a/src/utils/range/randomRangeDate.as b/src/utils/range/randomRangeDate.as index cea3c40..6268d48 100644 --- a/src/utils/range/randomRangeDate.as +++ b/src/utils/range/randomRangeDate.as @@ -1,43 +1,43 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 26, 2010 * Time: 1:59:33 PM */ package utils.range { /** * Returns a random date within a given range */ public function randomRangeDate(date1:Date, date2:Date) : Date { if(date1.getTime() == date2.getTime()){ - throw new Error("Dates specified are the same") + throw new Error("Dates specified are the same"); } if(date2.getTime() < date1.getTime() ){ var temp:Date = date1; date1 = date2; date2 = temp; } var diff:Number = date2.getTime() - date1.getTime(); var rand:Number = Math.random() * diff; var time:Number = date1.getTime() + rand; var d:Date = new Date(); - d.setTime(time) + d.setTime(time); return d; } } \ No newline at end of file diff --git a/src/utils/ratio/scaleHeight.as b/src/utils/ratio/scaleHeight.as index c7b66ed..ac94e2c 100644 --- a/src/utils/ratio/scaleHeight.as +++ b/src/utils/ratio/scaleHeight.as @@ -1,20 +1,17 @@ package utils.ratio { import flash.geom.Rectangle; - import utils.math.Percent; - - /** * Scales the height of an area while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param width Width to scale to * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleHeight(rect:Rectangle, width:Number, snapToPixel:Boolean = true):Rectangle { return defineRect(rect, width, width * heightToWidth(rect), snapToPixel); } } diff --git a/src/utils/ratio/scaleToFill.as b/src/utils/ratio/scaleToFill.as index e4e74df..73324a8 100644 --- a/src/utils/ratio/scaleToFill.as +++ b/src/utils/ratio/scaleToFill.as @@ -1,24 +1,21 @@ package utils.ratio { import flash.geom.Rectangle; - import utils.math.Percent; - - /** * Resizes an area to fill the bounding area while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param bounds Area to fill - the Rectangle's x and y values are ignored * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleToFill(rect:Rectangle, bounds:Rectangle, snapToPixel:Boolean = true):Rectangle { var scaled:Rectangle = scaleHeight(rect, bounds.width, snapToPixel); if(scaled.height < bounds.height) scaled = scaleWidth(rect, bounds.height, snapToPixel); return scaled; } } diff --git a/src/utils/ratio/scaleToFit.as b/src/utils/ratio/scaleToFit.as index 5497972..b47af73 100644 --- a/src/utils/ratio/scaleToFit.as +++ b/src/utils/ratio/scaleToFit.as @@ -1,24 +1,21 @@ package utils.ratio { import flash.geom.Rectangle; - import utils.math.Percent; - - /** * Resizes an area to the maximum size of a bounding area without exceeding while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param bounds Area the rectangle needs to fit within - the Rectangle's x and y values are ignored * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleToFit(rect:Rectangle, bounds:Rectangle, snapToPixel:Boolean = true):Rectangle { var scaled:Rectangle = scaleHeight(rect, bounds.width, snapToPixel); if(scaled.height > bounds.height) scaled = scaleWidth(rect, bounds.height, snapToPixel); return scaled; } } diff --git a/src/utils/ratio/scaleWidth.as b/src/utils/ratio/scaleWidth.as index b4381aa..908ab45 100644 --- a/src/utils/ratio/scaleWidth.as +++ b/src/utils/ratio/scaleWidth.as @@ -1,20 +1,16 @@ package utils.ratio { import flash.geom.Rectangle; - import utils.math.Percent; - - - /** * Scales the width of an area while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param height Height to scale to * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleWidth(rect:Rectangle, height:Number, snapToPixel:Boolean = true):Rectangle { return defineRect(rect, height * widthToHeight(rect), height, snapToPixel); } } diff --git a/src/utils/type/describeType.as b/src/utils/type/describeType.as index 1be0d12..56befc1 100644 --- a/src/utils/type/describeType.as +++ b/src/utils/type/describeType.as @@ -1,33 +1,33 @@ package utils.type { /** * Primary reflection method, producing an XML description of the object * or class specified. Results are cached internally for performance. * * @param value The object or class to introspect. * @param refreshCache Forces a new description to be generated, * useful only when a class alias has changed. * * @return An XML description, which format is * documented in the <code>flash.utils</code> * package. * * @see flash.utils#describeType */ - import flash.utils.describeType + import flash.utils.describeType; public function describeType(value:Object, refreshCache:Boolean = false):XML { if (!(value is Class)) { value = getType(value); } if (refreshCache || typeCache[value] == null) { typeCache[value] = flash.utils.describeType(value); } return typeCache[value]; } } \ No newline at end of file diff --git a/src/utils/type/isPassedByValue.as b/src/utils/type/isPassedByValue.as index 418f8ab..ce8b27c 100644 --- a/src/utils/type/isPassedByValue.as +++ b/src/utils/type/isPassedByValue.as @@ -1,30 +1,29 @@ package utils.type { - import flash.utils.*; /** * Checks to see if the class of <code>instance</code> is a primitive which will be copied by value * rather than by pointer. * The primitive types checked for are : * Number * int * uint * String * Boolean * * @author Mims Wright * * @param instance - the object whos class you want to check. * @return true if instance is is a primitive value or false if null or otherwise. */ public function isPassedByValue(instance:*):Boolean { if (instance == null) return false; //if (!isNaN(instance)) return true; if (instance is Number) return true; if (instance is int) return true; if (instance is uint) return true; if (instance is String) return true; if (instance is Boolean) return true; return false; } } \ No newline at end of file diff --git a/src/utils/type/isType.as b/src/utils/type/isType.as index 3b7ca38..6607be7 100644 --- a/src/utils/type/isType.as +++ b/src/utils/type/isType.as @@ -1,30 +1,31 @@ package utils.type { + import flash.utils.getQualifiedClassName; /** * Evaluates whether an object or class is derived from a specific * data type, class or interface. The isType() method is comparable to * ActionScript's <code>is</code> operator except that it also makes * class to class evaluations. * * @param value The object or class to evaluate. * @param type The data type to check against. * * @return True if the object or class is derived from * the data type. */ public function isType(value:Object, type:Class):Boolean { if (!(value is Class)) { return value is type; } if (value == type) { return true; } var inheritance:XMLList = describeInheritance(value); return Boolean(inheritance.(@type == getQualifiedClassName(type)).length() > 0); } } \ No newline at end of file diff --git a/src/utils/type/strictIs.as b/src/utils/type/strictIs.as index fc47c90..4ef7cd0 100755 --- a/src/utils/type/strictIs.as +++ b/src/utils/type/strictIs.as @@ -1,29 +1,27 @@ package utils.type { - import flash.utils.*; - /** * Checks the class of <code>instance</code> against the <code>compareClass</code> for strict * equality. If the classes are exactly the same, returns true. If * the classes are different even if the <code>instance</code>'s class is a subclass * of <code>compareClass</code>, it returns false. * Does not work with interfaces. The compareClass must be a class. * * @author Mims Wright * * @example <listing version="3.0"> * var myBase:BaseClass = new BaseClass(); * var mySub:SubClass = new SubClass(); * trace(strictIs(myBase, BaseClass)); // true * trace(strictIs(mySub, SubClass)); // true * trace(strictIs(mySub, BaseClass)); // false * </listing> * * @param instance - the object whos class you want to check. * @param compareClass - the class to compare your object against. * @return true if instance is strictly of type compareClass. */ public function strictIs(instance:Object, compareClass:Class):Boolean { return compareClass == Class(instance.constructor); } } \ No newline at end of file diff --git a/src/utils/validation/isValidCreditCardNumber.as b/src/utils/validation/isValidCreditCardNumber.as index f384690..b044172 100644 --- a/src/utils/validation/isValidCreditCardNumber.as +++ b/src/utils/validation/isValidCreditCardNumber.as @@ -1,74 +1,72 @@ package utils.validation { import utils.string.toNumeric; /** * Validate a credit card number as much as possible before submitting for approval. * @param strNumber credit card number as string * @example <listing version="3.0"> * var isValidNumber:Boolean = CreditCardValidator.isValidNumber("1234567890123456"); * </listing> */ public function isValidCreditCardNumber(strNumber:String):Boolean { - var mod10:Function = function mod10(strNumber:String):Boolean - { - - // Seperate each number into it's own index in an array. - var aNumbers:Array = strNumber.split(""); + var mod10:Function = function (strNumber:String):Boolean { + // Seperate each number into it's own index in an array. + var aNumbers:Array = strNumber.split(""); - // Hold the sums of some calculations that will be made shortly. - var nSum_1:Number = 0; - var nSum_2:Number = 0; - var nSum_Total:Number = 0; + // Hold the sums of some calculations that will be made shortly. + var nSum_1:Number = 0; + var nSum_2:Number = 0; + var nSum_Total:Number = 0; - // Check to see if the length of the card number is odd or even. This will - // be used to determine which indicies are doubled before being summed up. - var nParity:Number = aNumbers.length % 2; + // Check to see if the length of the card number is odd or even. This will + // be used to determine which indicies are doubled before being summed up. + var nParity:Number = aNumbers.length % 2; - // Loop through the card numbers. - for (var i:uint = 0; i < aNumbers.length; i++) - { - // Type cast each digit to a number. + // Loop through the card numbers. + for (var i:uint = 0; i < aNumbers.length; i++) + { + // Type cast each digit to a number. - var num:uint = uint(aNumbers[i]); + var num:uint = uint(aNumbers[i]); - aNumbers[i] = num; + aNumbers[i] = num; - // Compare the parity of the index to the parity of the card number length - // to determine how the value of the current index is handled. - if (i % 2 == nParity) - { - // Double each number. - aNumbers[i] *= 2; + // Compare the parity of the index to the parity of the card number length + // to determine how the value of the current index is handled. + if (i % 2 == nParity) + { + // Double each number. + aNumbers[i] *= 2; - // If the resulting value is greater than '9', subtract '9' from it. - aNumbers[i] = aNumbers[i] > 9 ? aNumbers[i] - 9 : aNumbers[i]; + // If the resulting value is greater than '9', subtract '9' from it. + aNumbers[i] = aNumbers[i] > 9 ? aNumbers[i] - 9 : aNumbers[i]; - // Add each value together. - nSum_1 += aNumbers[i]; - } - else - { - // Add each value together. - nSum_2 += aNumbers[i]; - } + // Add each value together. + nSum_1 += aNumbers[i]; + } + else + { + // Add each value together. + nSum_2 += aNumbers[i]; } - // Find the total sum of the two groups. - nSum_Total = nSum_1 + nSum_2; - - // If the sum is divisible by '10', the card number is valid. - return (nSum_Total % 10 == 0); } + // Find the total sum of the two groups. + nSum_Total = nSum_1 + nSum_2; + + // If the sum is divisible by '10', the card number is valid. + return (nSum_Total % 10 == 0); + }; const MINIMUM_CARD_LENGTH:int = 13; const MAXIMUM_CARD_LENGTH:int = 16; var ccNumber:String = toNumeric(strNumber); if (ccNumber.length > 0 && !isNaN(ccNumber as Number) && (ccNumber.length >= MINIMUM_CARD_LENGTH && ccNumber.length <= MAXIMUM_CARD_LENGTH)) { return mod10(ccNumber); } return false; } } \ No newline at end of file
as3/as3-utils
0617d97685bba57ad712587dca6beee226bfadca
hid flexunitapplication
diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..5671078 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1 @@ +FlexUnitApplication.mxml \ No newline at end of file diff --git a/src/FlexUnitApplication.mxml b/src/FlexUnitApplication.mxml deleted file mode 100644 index bfde487..0000000 --- a/src/FlexUnitApplication.mxml +++ /dev/null @@ -1,42 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> - -<!-- This is an auto generated file and is not intended for modification. --> - -<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" - xmlns:s="library://ns.adobe.com/flex/spark" - xmlns:mx="library://ns.adobe.com/flex/mx" - xmlns:flexui="flexunit.flexui.*" - minWidth="955" minHeight="600" creationComplete="onCreationComplete()"> - <fx:Script> - <![CDATA[ - import utils.validation.isValidPhoneNumberTest; - import utils.validation.isValidExpirationDateTest; - import utils.validation.isValidEmailAddress; - import utils.validation.isValidCreditCardNumberTest; - import utils.validation.isUSAStateAbbreviationTest; - - public function currentRunTestSuite():Array - { - var testsToRun:Array = new Array(); - testsToRun.push(utils.validation.isUSAStateAbbreviationTest); - testsToRun.push(utils.validation.isValidCreditCardNumberTest); - testsToRun.push(utils.validation.isValidEmailAddress); - testsToRun.push(utils.validation.isValidExpirationDateTest); - testsToRun.push(utils.validation.isValidPhoneNumberTest); - return testsToRun; - } - - - private function onCreationComplete():void - { - testRunner.runWithFlexUnit4Runner(currentRunTestSuite(), "as3-utils"); - } - - ]]> - </fx:Script> - <fx:Declarations> - <!-- Place non-visual elements (e.g., services, value objects) here --> - </fx:Declarations> - <flexui:FlexUnitTestRunnerUI id="testRunner"> - </flexui:FlexUnitTestRunnerUI> -</s:Application>
as3/as3-utils
f9a52fd2272acd075de4b437f43ef7726ad65add
modified gitignore to hide flexunit stuff
diff --git a/.gitignore b/.gitignore index 379fde3..5a2139e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,12 @@ target bin bin-debug bin-release *.iml -.actionScriptProperties -.flexLibProperties +.actionScript* +.flex* +.Flex* .project .settings/ .DS_Store org.eclipse.core.resources.prefs \ No newline at end of file
as3/as3-utils
de767124744eca9076878b2ea03c0df9a92d9e6b
modified a couple of functions
diff --git a/src/FlexUnitApplication.mxml b/src/FlexUnitApplication.mxml new file mode 100644 index 0000000..bfde487 --- /dev/null +++ b/src/FlexUnitApplication.mxml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- This is an auto generated file and is not intended for modification. --> + +<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + xmlns:mx="library://ns.adobe.com/flex/mx" + xmlns:flexui="flexunit.flexui.*" + minWidth="955" minHeight="600" creationComplete="onCreationComplete()"> + <fx:Script> + <![CDATA[ + import utils.validation.isValidPhoneNumberTest; + import utils.validation.isValidExpirationDateTest; + import utils.validation.isValidEmailAddress; + import utils.validation.isValidCreditCardNumberTest; + import utils.validation.isUSAStateAbbreviationTest; + + public function currentRunTestSuite():Array + { + var testsToRun:Array = new Array(); + testsToRun.push(utils.validation.isUSAStateAbbreviationTest); + testsToRun.push(utils.validation.isValidCreditCardNumberTest); + testsToRun.push(utils.validation.isValidEmailAddress); + testsToRun.push(utils.validation.isValidExpirationDateTest); + testsToRun.push(utils.validation.isValidPhoneNumberTest); + return testsToRun; + } + + + private function onCreationComplete():void + { + testRunner.runWithFlexUnit4Runner(currentRunTestSuite(), "as3-utils"); + } + + ]]> + </fx:Script> + <fx:Declarations> + <!-- Place non-visual elements (e.g., services, value objects) here --> + </fx:Declarations> + <flexui:FlexUnitTestRunnerUI id="testRunner"> + </flexui:FlexUnitTestRunnerUI> +</s:Application> diff --git a/src/utils/date/Timezone.as b/src/utils/date/Timezone.as index ad0a6d6..e61408f 100644 --- a/src/utils/date/Timezone.as +++ b/src/utils/date/Timezone.as @@ -1,92 +1,95 @@ package utils.date { /* * Need to discuss how to refactor timezone logic into better utils * * This class currently only works with USA (the offsets default to EAST if the timezone is outside of the USA. * * */ public class Timezone { public static const EAST:String = "ET"; public static const WEST:String = "WT"; public static const ARIZONA:String = "AZ"; public static const MOUNTAIN:String = "MT"; public static const CENTRAL:String = "CT"; public static const PACIFIC:String = "PT"; public static const ALASKA:String = "AK"; public static const HAWAII:String = "HT"; private static var nonDstOffsetDate:Date = new Date(2010, 1, 1); private static var dstOffsetDate:Date = new Date(2010, 7, 1); private static var observesDST:Boolean = (nonDstOffsetDate.timezoneOffset != dstOffsetDate.timezoneOffset); private static var timezone:String = EAST; public static function get zuluOffset():String { var offset:Number = nonDstOffsetDate.timezoneOffset / 60; if(offset > 11 || offset <= 5) { offset = 4; //defaulting to east coast return String(offset); } return String(new Date().timezoneOffset / 60); } public static function get dstOffset():String { var offset:Number = dstOffsetDate.timezoneOffset / 60; if(offset > 10 || offset <= 4) { offset = 4; //defaulting to east coast } return String(offset); } public static function get nonDstOffset():String { var offset:Number = nonDstOffsetDate.timezoneOffset / 60; if(offset > 11 || offset <= 5) { offset = 5; //defaulting to east coast } return String(offset); } public static function get name():String { //Default to Eastern switch (nonDstOffset) { case "10": timezone = HAWAII; //Hawaii break; case "9": timezone = ALASKA; //Alaska break; case "8": timezone = PACIFIC;//Pacific break; case "7": timezone = MOUNTAIN;//Mountain if(!observesDST) timezone = ARIZONA; break; case "6": timezone = CENTRAL;//Central break; + + default: + timezone = EAST; } return timezone; } } } diff --git a/test/utils/validation/isUSAStateAbbreviationTest.as b/test/utils/validation/isUSAStateAbbreviationTest.as index 7e83884..3e01f0b 100644 --- a/test/utils/validation/isUSAStateAbbreviationTest.as +++ b/test/utils/validation/isUSAStateAbbreviationTest.as @@ -1,26 +1,27 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:24 AM */ package utils.validation { import org.flexunit.asserts.fail; import org.flexunit.flexui.patterns.AssertThatPattern; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class isUSAStateAbbreviationTest { [Test] public function isUSAStateAbbreviationTest() { new Array('ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy'); -// assertThat(isUSAStateAbbreviation("DE"),equalTo()) +// assertThat(isUSAStateAbbreviation("DE"), +// equalTo()) fail("test remains to be implemented") } } }
as3/as3-utils
a8259f48d848acb79818550fd0cdedf1fefbb3c2
fixed compile error by commenting
diff --git a/test/utils/validation/isUSAStateAbbreviationTest.as b/test/utils/validation/isUSAStateAbbreviationTest.as index ca804cd..7e83884 100644 --- a/test/utils/validation/isUSAStateAbbreviationTest.as +++ b/test/utils/validation/isUSAStateAbbreviationTest.as @@ -1,26 +1,26 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:24 AM */ package utils.validation { import org.flexunit.asserts.fail; import org.flexunit.flexui.patterns.AssertThatPattern; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class isUSAStateAbbreviationTest { [Test] public function isUSAStateAbbreviationTest() { new Array('ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy'); - assertThat(isUSAStateAbbreviation("DE"),equalTo()) +// assertThat(isUSAStateAbbreviation("DE"),equalTo()) fail("test remains to be implemented") } } }
as3/as3-utils
2a9f347e0a3e2d355f1c8c80df4a318cba87ab53
modified state abbreviations
diff --git a/src/utils/validation/US_STATE_ABBREVIATIONS.as b/src/utils/validation/US_STATE_ABBREVIATIONS.as new file mode 100644 index 0000000..ebc9777 --- /dev/null +++ b/src/utils/validation/US_STATE_ABBREVIATIONS.as @@ -0,0 +1,5 @@ +package utils.validation +{ + public const US_STATE_ABBREVIATIONS:Array = ['ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', + 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy']; +} \ No newline at end of file diff --git a/src/utils/validation/isUSAStateAbbreviation.as b/src/utils/validation/isUSAStateAbbreviation.as index e22c7f6..b26dbc6 100644 --- a/src/utils/validation/isUSAStateAbbreviation.as +++ b/src/utils/validation/isUSAStateAbbreviation.as @@ -1,18 +1,15 @@ package utils.validation { import utils.array.contains; /** Determines if String is a valid USA state abbreviation. @param state: String to verify as two letter state abbreviation (includes DC). @return Returns <code>true</code> if String is a state abbreviation; otherwise <code>false</code>. */ public function isUSAStateAbbreviation(state:String):Boolean { - var states:Array = - new Array('ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', - 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy'); - return contains(states, state.toLowerCase()) == 1; + return contains(US_STATE_ABBREVIATIONS, state.toLowerCase()) == 1; } } \ No newline at end of file
as3/as3-utils
2d560a061db5757385fa3ae4487d5ad65902d4f8
finished test coverage for items in the validation package
diff --git a/test/UtilsTestRunner.as b/test/UtilsTestRunner.as deleted file mode 100644 index dd297a2..0000000 --- a/test/UtilsTestRunner.as +++ /dev/null @@ -1,31 +0,0 @@ -package -{ - import flash.display.Sprite; - - import org.flexunit.internals.TraceListener; - import org.flexunit.listeners.CIListener; - import org.flexunit.runner.FlexUnitCore; - - import utils.UtilsTestSuite; - - [SWF] - - public class UtilsTestRunner extends Sprite - { - public var core:FlexUnitCore; - - public function UtilsTestRunner() - { - super(); - run(); - } - - public function run():void - { - core = new FlexUnitCore(); - core.addListener(new TraceListener()); - core.addListener(new CIListener()); - core.run(UtilsTestSuite); - } - } -} \ No newline at end of file diff --git a/test/utils/UtilsTestSuite.as b/test/utils/UtilsTestSuite.as deleted file mode 100644 index 7dc7cf0..0000000 --- a/test/utils/UtilsTestSuite.as +++ /dev/null @@ -1,9 +0,0 @@ -package utils -{ - [Suite] - [RunWith("org.flexunit.runners.Suite")] - public class UtilsTestSuite - { - - } -} \ No newline at end of file diff --git a/test/utils/validation/encodeCreditCardNumberTest.as b/test/utils/validation/encodeCreditCardNumberTest.as new file mode 100644 index 0000000..546858f --- /dev/null +++ b/test/utils/validation/encodeCreditCardNumberTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 3:07 PM + */ +package utils.validation { +public class encodeCreditCardNumberTest { + public function encodeCreditCardNumberTest() { + } +} +} diff --git a/test/utils/validation/getCreditCardProviderTest.as b/test/utils/validation/getCreditCardProviderTest.as new file mode 100644 index 0000000..c8fad39 --- /dev/null +++ b/test/utils/validation/getCreditCardProviderTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 1:26 PM + */ +package utils.validation { +public class getCreditCardProviderTest { + public function getCreditCardProviderTest() { + } +} +} diff --git a/test/utils/validation/isBlankTest.as b/test/utils/validation/isBlankTest.as new file mode 100644 index 0000000..4847299 --- /dev/null +++ b/test/utils/validation/isBlankTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:48 AM + */ +package utils.validation { +public class isBlankTest { + public function isBlankTest() { + } +} +} diff --git a/test/utils/validation/isCreditCardTest.as b/test/utils/validation/isCreditCardTest.as new file mode 100644 index 0000000..5365602 --- /dev/null +++ b/test/utils/validation/isCreditCardTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:44 AM + */ +package utils.validation { +public class isCreditCardTest { + public function isCreditCardTest() { + } +} +} diff --git a/test/utils/validation/isEmailTest.as b/test/utils/validation/isEmailTest.as new file mode 100644 index 0000000..9590865 --- /dev/null +++ b/test/utils/validation/isEmailTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:39 AM + */ +package utils.validation { +public class isEmailTest { + public function isEmailTest() { + } +} +} diff --git a/test/utils/validation/isNumericTest.as b/test/utils/validation/isNumericTest.as new file mode 100644 index 0000000..2a4e80a --- /dev/null +++ b/test/utils/validation/isNumericTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:37 AM + */ +package utils.validation { +public class isNumericTest { + public function isNumericTest() { + } +} +} diff --git a/test/utils/validation/isPOBoxTest.as b/test/utils/validation/isPOBoxTest.as new file mode 100644 index 0000000..e16ccf6 --- /dev/null +++ b/test/utils/validation/isPOBoxTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:35 AM + */ +package utils.validation { +public class isPOBoxTest { + public function isPOBoxTest() { + } +} +} diff --git a/test/utils/validation/isUSAStateAbbreviationTest.as b/test/utils/validation/isUSAStateAbbreviationTest.as new file mode 100644 index 0000000..ca804cd --- /dev/null +++ b/test/utils/validation/isUSAStateAbbreviationTest.as @@ -0,0 +1,26 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:24 AM + */ +package utils.validation { +import org.flexunit.asserts.fail; +import org.flexunit.flexui.patterns.AssertThatPattern; +import org.hamcrest.assertThat; +import org.hamcrest.object.equalTo; + +public class isUSAStateAbbreviationTest { + + [Test] + public function isUSAStateAbbreviationTest() { + + new Array('ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', + 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy'); + + assertThat(isUSAStateAbbreviation("DE"),equalTo()) + + fail("test remains to be implemented") + } +} +} diff --git a/test/utils/validation/isUrlTest.as b/test/utils/validation/isUrlTest.as new file mode 100644 index 0000000..06adbf4 --- /dev/null +++ b/test/utils/validation/isUrlTest.as @@ -0,0 +1,12 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/24/11 + * Time: 11:29 AM + */ +package utils.validation { +public class isUrlTest { + public function isUrlTest() { + } +} +} diff --git a/test/validation/isValidCreditCardNumberTest.as b/test/utils/validation/isValidCreditCardNumberTest.as similarity index 98% rename from test/validation/isValidCreditCardNumberTest.as rename to test/utils/validation/isValidCreditCardNumberTest.as index 47adb86..7f76bc4 100644 --- a/test/validation/isValidCreditCardNumberTest.as +++ b/test/utils/validation/isValidCreditCardNumberTest.as @@ -1,70 +1,70 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:52 PM */ -package validation { +package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidCreditCardNumber; public class isValidCreditCardNumberTest { [Test] public function ccBelowMinimum13ShouldFail() : void { assertThat(isValidCreditCardNumber("1234"), equalTo(false)); } [Test] public function ccAboveMaximum16ShouldFail() : void { assertThat(isValidCreditCardNumber("123413123123213421341123412423412412341232314"), equalTo(false)); } //Even CC length integrity testing //Each number is examined //if a number is divisible by 2 with no remainder (even) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. //if a number is divisible by 2 with a remainder (odd) it gets added to the second group //The first group plus the second group should be divisible by 10 with no remainder [Test] public function ccEvenNumberLengthWithBadIntegrityShouldFail() : void { assertThat(isValidCreditCardNumber("12345678901234"), equalTo(false)); } [Test] public function ccEvenNumberLengthWithGoodIntegrityShouldPass() : void { assertThat(isValidCreditCardNumber("72345678901234"), equalTo(true)); } //Odd CC length integrity testing //Each number is examined //if a number is divisible by 1 with no remainder (odd) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. //if a number is divisible by 1 with a remainder (even) it gets added to the second group //The first group plus the second group should be divisible by 10 with no remainder [Test] public function ccOddNumberLengthWithBadIntegrityShouldFail() : void { assertThat(isValidCreditCardNumber("123456789012345"), equalTo(false)); } [Test] public function ccOddNumberLengthWithGoodIntegrityShouldPass() : void { assertThat(isValidCreditCardNumber("323456789012345"), equalTo(true)); } } } diff --git a/test/validation/isValidEmailAddress.as b/test/utils/validation/isValidEmailAddress.as similarity index 97% rename from test/validation/isValidEmailAddress.as rename to test/utils/validation/isValidEmailAddress.as index 367508e..13f2fe5 100644 --- a/test/validation/isValidEmailAddress.as +++ b/test/utils/validation/isValidEmailAddress.as @@ -1,43 +1,43 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:47 PM */ -package validation { +package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidEmailAddress; public class isValidEmailAddress { [Test] public function goodEmailPasses() : void { assertThat(utils.validation.isValidEmailAddress("[email protected]"), equalTo(true)) } [Test] public function emailWithSpaceFails() : void { assertThat(utils.validation.isValidEmailAddress("test@ test.com"), equalTo(false)) } [Test] public function emailWithoutAtSymbolFails() : void { assertThat(utils.validation.isValidEmailAddress("testtest.com"), equalTo(false)) } [Test] public function emailWithInvalidCharacterFails() : void { assertThat(utils.validation.isValidEmailAddress("test@te$t.com"), equalTo(false)) } } } diff --git a/test/validation/isValidExpirationDateTest.as b/test/utils/validation/isValidExpirationDateTest.as similarity index 97% rename from test/validation/isValidExpirationDateTest.as rename to test/utils/validation/isValidExpirationDateTest.as index d7f0cf9..950a00c 100644 --- a/test/validation/isValidExpirationDateTest.as +++ b/test/utils/validation/isValidExpirationDateTest.as @@ -1,51 +1,51 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:34 PM */ -package validation { +package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidExpirationDate; public class isValidExpirationDateTest { [Test] public function expirationOfNextYearShouldPass() : void { assertThat(isValidExpirationDate(1, new Date().getFullYear() + 1), equalTo(true)); } [Test] public function expirationOfLastYearShouldFail() : void { assertThat(isValidExpirationDate(1, new Date().getFullYear() - 1), equalTo(false)); } [Test] public function expirationOfSameYearButUpcomingMonthShouldPass() : void { assertThat(isValidExpirationDate(new Date().getMonth() + 1, new Date().getFullYear()), equalTo(true)); } [Test] public function expirationOfSameYearButPastMonthShouldFail() : void { assertThat(isValidExpirationDate(new Date().getMonth() - 1, new Date().getFullYear()), equalTo(false)); } [Test] public function expirationOfUpcomingYearWithMonthOfZeroShouldFail() : void { assertThat(isValidExpirationDate(0,new Date().getFullYear() + 1), equalTo(true)); } } } diff --git a/test/validation/isValidPhoneNumberTest.as b/test/utils/validation/isValidPhoneNumberTest.as similarity index 96% rename from test/validation/isValidPhoneNumberTest.as rename to test/utils/validation/isValidPhoneNumberTest.as index 640d67c..27cb87b 100644 --- a/test/validation/isValidPhoneNumberTest.as +++ b/test/utils/validation/isValidPhoneNumberTest.as @@ -1,40 +1,40 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 5:32 PM */ -package validation { +package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidPhoneNumber; public class isValidPhoneNumberTest { [Test] public function validNumberPasses() : void { assertThat(isValidPhoneNumber("123 456-7789"), equalTo(true)); } [Test] public function validNumberNoDashesPasses() : void { assertThat(isValidPhoneNumber("123 456 7789"), equalTo(true)); } //TODO: Should this be the intended behavior? [Test] public function validNumberWithPrefixFails() : void { assertThat(isValidPhoneNumber("1 123 456-7789"), equalTo(false)); } } }
as3/as3-utils
eeac8154e87c550161b1985781453cd66c476ef3
added functionality to toHex. Added getTimeElapsedString. added and updated tests for several functions. added isPassedByValue
diff --git a/src/utils/date/getTimeElapsedString.as b/src/utils/date/getTimeElapsedString.as new file mode 100644 index 0000000..f3f4812 --- /dev/null +++ b/src/utils/date/getTimeElapsedString.as @@ -0,0 +1,76 @@ +package utils.date +{ + /** + * Takes a Date object and returns a string in the format + * "X UNITS ago" where X is a number and UNITS is a unit of + * time. Also has some other strings like "yesterday". + * + * @author Mims Wright (with thanks to John Resig) + * + * @param date The date to convert to a past string. + * @param now Optional time to compare against. Default will be the present. + */ + public function getTimeElapsedString(date:Date, now:Date = null):String { + + const SEC_PER_MINUTE:int = 60; + const SEC_PER_HOUR:int = SEC_PER_MINUTE * 60; + const SEC_PER_DAY:int = SEC_PER_HOUR * 24; + const SEC_PER_WEEK:int = SEC_PER_DAY * 7; + const SEC_PER_MONTH:int = SEC_PER_DAY * 30; + const SEC_PER_YEAR:int = SEC_PER_MONTH * 12; + + // if now isn't defined, make it a new Date object (the present) + if (!now) { now = new Date(); } + + // don't use secondsElapsed here because the values are + // huge so they use uints and are never negative + if (now.time < date.time) { return "in the future"; } + + // get the difference in seconds between the two values. + var secondsElapsed:uint = Math.floor((now.time - date.time) / 1000); + + + // seconds + if (secondsElapsed < SEC_PER_MINUTE) { return "just now"; } + + // minutes + if (secondsElapsed < SEC_PER_HOUR) { + var minutes:int = int(secondsElapsed / SEC_PER_MINUTE); + return formatAgoString(minutes, "minute"); + } + + // hours + if (secondsElapsed < SEC_PER_DAY) { + var hours:int = int(secondsElapsed / SEC_PER_HOUR); + return formatAgoString(hours, "hour"); + } + + // days + if (secondsElapsed < SEC_PER_WEEK) { + var days:int = int(secondsElapsed / SEC_PER_DAY); + if (days == 1) { return "yesterday"; } + + return formatAgoString(days, "day"); + } + + // weeks + if (secondsElapsed < SEC_PER_MONTH) { + var weeks:int = int(secondsElapsed / SEC_PER_WEEK); + return formatAgoString(weeks, "week"); + } + + // months + if (secondsElapsed < SEC_PER_YEAR) { + var months:int = int(secondsElapsed / SEC_PER_MONTH); + return formatAgoString(months, "month"); + } + + // years + return "more than a year ago"; + + // Returns a string in the format "count unit(s) ago" + function formatAgoString(count:int, unit:String):String { + return count + " " + unit + (count > 1 ? "s" : "") + " ago"; + } + } +} \ No newline at end of file diff --git a/src/utils/number/toHex.as b/src/utils/number/toHex.as index 03ee7d8..183c2b9 100644 --- a/src/utils/number/toHex.as +++ b/src/utils/number/toHex.as @@ -1,43 +1,71 @@ package utils.number { import flash.utils.Endian; /** - * Outputs the hex value of a int, allowing the developer to specify - * the endian in the process. Hex output is lowercase. - * @param n The int value to output as hex + * Converts a uint into a string in the format “0x123456789ABCDEF”. + * This function is quite useful for displaying hex colors as text. + * + * @example + * <listing version="3.0"> + * getNumberAsHexString(255); // 0xFF + * getNumberAsHexString(0xABCDEF); // 0xABCDEF + * getNumberAsHexString(0x00FFCC); // 0xFFCC + * getNumberAsHexString(0x00FFCC, 6); // 0x00FFCC + * getNumberAsHexString(0x00FFCC, 6, false); // 00FFCC + * getNumberAsHexString(0x12345, 1, false, Endian.BIG_ENDIAN); // 452301 (note 0 added to 1 to make a byte) + * </listing> + * + * + * @param number The number to convert to hex. Note, numbers larger than 0xFFFFFFFF may produce unexpected results. + * @param minimumLength The smallest number of hexits to include in the output. + * Missing places will be filled in with 0’s. + * e.g. getNumberAsHexString(0xFF33, 6); // results in "0x00FF33" + * @param showHexDenotation If true, will append "0x" to the front of the string. * @param endianness Flag to output the int as big or little endian. - * Can be Endian.BIG_INDIAN/Endian.LITTLE_ENDIAN or true/false - * @return A string of length 8 corresponding to the - * hex representation of n ( minus the leading "0x" ) + * Can be Endian.BIG_INDIAN/Endian.LITTLE_ENDIAN or true/false. + * Default is BIG. + * @return String representation of the number as a string starting with "0x" * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @see flash.utils.Endian * - * @author Unknown. flash.utils.Endian tweak added by Mims Wright + * @author Mims H. Wright (modified by Pimm Hogeling) */ - public function toHex(n:int, endianness:* = null):String { + public function toHex(n:int, minimumLength:uint = 1, showHexDenotation:Boolean = true, endianness:* = null):String { var bigEndian:Boolean; - if (endianness == null) { endianness = Endian.LITTLE_ENDIAN; } + if (endianness == null) { endianness = Endian.BIG_ENDIAN; } if (endianness is Boolean) { bigEndian = Boolean(endianness); } else { bigEndian = endianness == Endian.BIG_ENDIAN; } - var s:String = ""; - - if(bigEndian) { - for(var i:int = 0; i < 4; i++) { - s += hexChars.charAt((n >> ((3 - i) * 8 + 4)) & 0xF) + hexChars.charAt((n >> ((3 - i) * 8)) & 0xF); - } + + // The string that will be output at the end of the function. + var string:String = n.toString(16).toUpperCase(); + + // While the minimumLength argument is higher than the length of the string, add a leading zero. + while (minimumLength > string.length) { + string = "0" + string; } - else { - for(var x:int = 0; x < 4; x++) { - s += hexChars.charAt((n >> (x * 8 + 4)) & 0xF) + hexChars.charAt((n >> (x * 8)) & 0xF); + + if (!bigEndian) { + // reverse string. + if (string.length %2 == 1) { string = "0" + string; } + var i:int = 0; + var reversed:Array = []; + while (i < string.length) { + var byte:String = string.charAt(i++) + string.charAt(i++); + reversed.unshift(byte); } + string = reversed.join(""); + } - - return s; + + // Return the result with a "0x" in front of the result. + if (showHexDenotation) { string = "0x" + string; } + + return string; } } diff --git a/src/utils/object/clone.as b/src/utils/object/clone.as index dea45e1..2d49383 100644 --- a/src/utils/object/clone.as +++ b/src/utils/object/clone.as @@ -1,18 +1,39 @@ package utils.object { + import flash.net.registerClassAlias; import flash.utils.ByteArray; + import flash.utils.getQualifiedClassName; - /** - * Creates a generic object clone of a given object. Does <strong>not</strong> retain type. - * - * @param obj - * @return - */ - public function clone(obj:Object):Object - { - const byt:ByteArray = new ByteArray(); - byt.writeObject(obj); - byt.position = 0; - return byt.readObject(); + /** + * Creates a duplicate of the source object by storing it in a ByteArray and reading it back in, + * The object will return untyped so you may need to cast it to the desired class. + * AMF rules apply. Check out the documentation for more info. + * NOTE: This will not work if the object has any required parameters in the constructor. + * + * @throws flash.errors.ArgumentError If the source's constructor requires any parameters. + * + * @example + * <listing version="3.0"> + * var example:Example = new Example(); + * var clone:Example = Cloner.clone(example) as Example; + * </listing> + * + * @see flash.net#registerClassAlias() + * + * @param source The object to duplicate. + * @param autoRegisterClassAlias Determines whether the class will be registered before cloning. + * Defaults to true, though advanced users may wish to register class aliases manually. + * @return * A duplicate of the source object. + * + * @author Mims Wright + */ + public function clone(source:Object, autoRegisterClassAlias:Boolean = true):* { + // automatically register the class so that the clone retains its class. + if (autoRegisterClassAlias) registerClassAlias(getQualifiedClassName(source), source.constructor as Class); + + var copy:ByteArray = new ByteArray(); + copy.writeObject(source); + copy.position = 0; + return copy.readObject(); } } \ No newline at end of file diff --git a/src/utils/object/contains.as b/src/utils/object/contains.as index 31a143c..8b3ab8d 100644 --- a/src/utils/object/contains.as +++ b/src/utils/object/contains.as @@ -1,25 +1,23 @@ package utils.object { /** * Searches the first level properties of an Object for a another Object. * @param obj Object to search in. * @param member Object to search for. * @return true if Object was found * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function contains(obj:Object, member:Object):Boolean { - var out:Boolean; - for(var prop:String in obj) { if(obj[prop] == member) { - out = true; + return true; } } - return out; + return false; } } diff --git a/src/utils/type/isPassedByValue.as b/src/utils/type/isPassedByValue.as new file mode 100644 index 0000000..418f8ab --- /dev/null +++ b/src/utils/type/isPassedByValue.as @@ -0,0 +1,30 @@ +package utils.type +{ + import flash.utils.*; + + /** + * Checks to see if the class of <code>instance</code> is a primitive which will be copied by value + * rather than by pointer. + * The primitive types checked for are : + * Number + * int + * uint + * String + * Boolean + * + * @author Mims Wright + * + * @param instance - the object whos class you want to check. + * @return true if instance is is a primitive value or false if null or otherwise. + */ + public function isPassedByValue(instance:*):Boolean { + if (instance == null) return false; + //if (!isNaN(instance)) return true; + if (instance is Number) return true; + if (instance is int) return true; + if (instance is uint) return true; + if (instance is String) return true; + if (instance is Boolean) return true; + return false; + } +} \ No newline at end of file diff --git a/test/utils/date/GetTimeElapsedStringTest.as b/test/utils/date/GetTimeElapsedStringTest.as new file mode 100644 index 0000000..5d10f7f --- /dev/null +++ b/test/utils/date/GetTimeElapsedStringTest.as @@ -0,0 +1,42 @@ +package utils.date +{ + import flexunit.framework.Assert; + + import utils.date.getTimeElapsedString; + + /** + * DateFormatterTest + * + * @author Mims H. Wright + */ + public class GetTimeElapsedStringTest + { + [Test] + public function testGetTimeElapsedString():void { + + // create a custom date for now to ensure that subtracting time from + // each field will create a valid date + var now:Date = new Date(2010, 11, 30, 12, 50, 50); + + var secondsAgo:Date = new Date(now.fullYear, now.month, now.date, now.hours, now.minutes, now.seconds - 5); + var minutesAgo:Date = new Date(now.fullYear, now.month, now.date, now.hours, now.minutes - 5); + var hoursAgo:Date = new Date(now.fullYear, now.month, now.date, now.hours - 5); + var yesterday:Date = new Date(now.fullYear, now.month, now.date - 1); + var daysAgo:Date = new Date(now.fullYear, now.month, now.date - 5); + var weeksAgo:Date = new Date(now.fullYear, now.month, now.date - 8); + var monthsAgo:Date = new Date(now.fullYear, now.month - 5, now.date ); + var yearsAgo:Date = new Date(now.fullYear - 2, now.month, now.date); + var future:Date = new Date(now.fullYear + 1, now.month, now.date); + + Assert.assertEquals("just now", getTimeElapsedString(secondsAgo, now)); + Assert.assertEquals("5 minutes ago", getTimeElapsedString(minutesAgo, now)); + Assert.assertEquals("5 hours ago", getTimeElapsedString(hoursAgo, now)); + Assert.assertEquals("yesterday", getTimeElapsedString(yesterday, now)); + Assert.assertEquals("5 days ago", getTimeElapsedString(daysAgo, now)); + Assert.assertEquals("1 week ago", getTimeElapsedString(weeksAgo, now)); + Assert.assertEquals("5 months ago", getTimeElapsedString(monthsAgo, now)); + Assert.assertEquals("more than a year ago", getTimeElapsedString(yearsAgo, now)); + Assert.assertEquals("in the future", getTimeElapsedString(future, now)); + } + } +} \ No newline at end of file diff --git a/test/utils/dictionary/CircularDictionaryTest.as b/test/utils/dictionary/CircularDictionaryTest.as new file mode 100644 index 0000000..223b01e --- /dev/null +++ b/test/utils/dictionary/CircularDictionaryTest.as @@ -0,0 +1,24 @@ +package utils.dictionary +{ + import flexunit.framework.Assert; + + import utils.dictionary.CircularDictionary; + + public class CircularDictionaryTest + { + [Test] + public function testAddAndRemovePair():void { + var a:Object = {foo:"bar"}; + var b:int = 42; + + var dict:CircularDictionary = new CircularDictionary(); + dict.addPair(a,b); + Assert.assertEquals(a, dict.getCounterpartTo(b)); + Assert.assertEquals(b, dict.getCounterpartTo(a)); + + var result:* = dict.removePair(a); + Assert.assertUndefined(dict.getCounterpartTo(a), dict.getCounterpartTo(b)); + Assert.assertEquals(result, b); + } + } +} \ No newline at end of file diff --git a/test/utils/number/ClampTest.as b/test/utils/number/ClampTest.as new file mode 100644 index 0000000..4523681 --- /dev/null +++ b/test/utils/number/ClampTest.as @@ -0,0 +1,20 @@ +package utils.number +{ + import flexunit.framework.Assert; + + import utils.number.clamp; + + public class ClampTest + { + [Test] + public function testClamp():void { + var low:int = 0; + var high:int = 100; + + Assert.assertEquals("Values between low and high are passed thru.", clamp(50, low, high), 50); + Assert.assertEquals("Values lower than low value are limited to the low value.", clamp(low - 100, low, high), low); + Assert.assertEquals("Values higher than the high value are limited to the high value.", clamp(high + 100, low, high), high); + Assert.assertEquals("If any values are NaN, return NaN.", clamp(5, NaN, high), NaN); + } + } +} \ No newline at end of file diff --git a/test/utils/number/ToHexTest.as b/test/utils/number/ToHexTest.as new file mode 100644 index 0000000..148035d --- /dev/null +++ b/test/utils/number/ToHexTest.as @@ -0,0 +1,26 @@ +package utils.number +{ + import flash.utils.Endian; + + import flexunit.framework.Assert; + + import utils.number.toHex; + import utils.string.endsWith; + + public class ToHexTest + { + [Test] + public function testToHex ():void { + Assert.assertEquals("Big endian", "0xFC00", toHex(0xFC00, 1, true, Endian.BIG_ENDIAN)); + Assert.assertEquals("Little endian", "0x00FC", toHex(0xFC00, 1, true, Endian.LITTLE_ENDIAN)); + Assert.assertEquals("Add leading 0 if there aren't enough numbers to make a byte", "0x452301", toHex(0x12345, 1, true, Endian.LITTLE_ENDIAN)); + Assert.assertEquals("Converting from digital number to hex produces hex string", "0xFF", toHex(255)); + Assert.assertEquals("Convert 0 to 0x0", "0x0", toHex(0)); + Assert.assertEquals("Floats round down", "0x1", toHex(1.6)); + Assert.assertEquals("Converting from hex number to hex produces hex string", "0xABCDEF", toHex(0xABCDEF)); + Assert.assertEquals("Hide '0x'", "ABC", toHex(0xABC, 1, false)); + Assert.assertEquals("Leading 0's", "0x0033CC", toHex(0x0033CC, 6)); + // todo: test endian param. + } + } +} \ No newline at end of file diff --git a/test/utils/object/containsTest.as b/test/utils/object/containsTest.as new file mode 100644 index 0000000..eeb23b6 --- /dev/null +++ b/test/utils/object/containsTest.as @@ -0,0 +1,19 @@ +package utils.object +{ + import flexunit.framework.Assert; + import utils.object.contains; + + public class containsTest + { + [Test] + public function testContains():void { + var o:Object = {foo:"bar", baz:42}; + var p:Object = {foo:o}; + + Assert.assertTrue("Object contains 'bar'", contains(o, "bar")); + Assert.assertFalse("Doesn't check property names", contains(o, "foo")); + Assert.assertTrue("Object contains other objects", contains(p, o)); + } + + } +} \ No newline at end of file diff --git a/test/utils/type/IsPassedByValueTest.as b/test/utils/type/IsPassedByValueTest.as new file mode 100644 index 0000000..45a3dda --- /dev/null +++ b/test/utils/type/IsPassedByValueTest.as @@ -0,0 +1,27 @@ +package utils.type +{ + import flexunit.framework.Assert; + + import utils.type.isPassedByValue; + + public class IsPassedByValueTest + { + [Test] + public function testIsPassedByValue():void { + Assert.assertTrue("uint is passed by value", isPassedByValue(uint(5))); + Assert.assertTrue("int is passed by value", isPassedByValue(int(5))); + Assert.assertTrue("Number is passed by value", isPassedByValue(5.5)); + Assert.assertTrue("String is passed by value", isPassedByValue("foo")); + Assert.assertTrue("Boolean is passed by value", isPassedByValue(true)); + + Assert.assertFalse("null values don't indicate the type of the variable container.", isPassedByValue(null)); + + var xml:XML = + <body> + <p>hello</p> + </body>; + Assert.assertFalse("XML is not passed by value even though it's a primitive", isPassedByValue(xml)); + } + + } +} \ No newline at end of file diff --git a/test/utils/type/StrictIsTest.as b/test/utils/type/StrictIsTest.as new file mode 100644 index 0000000..b36af43 --- /dev/null +++ b/test/utils/type/StrictIsTest.as @@ -0,0 +1,27 @@ +package utils.type +{ + import flash.display.MovieClip; + import flash.display.Sprite; + + import flexunit.framework.Assert; + + import utils.type.strictIs; + + public class StrictIsTest + { + [Test] + public function testStrictIs():void { + var s:Sprite = new Sprite(); + var m:MovieClip = new MovieClip(); + + Assert.assertTrue("Sprite instance is Sprite", s is Sprite); + Assert.assertTrue("MovieClip instance is Sprite", m is Sprite); + Assert.assertFalse("Sprite instance is not MovieClip", s is MovieClip); + + Assert.assertTrue("Sprite instance is strictly Sprite", strictIs(s, Sprite)); + Assert.assertFalse("MovieClip instance is strictly not a Sprite", strictIs(m, Sprite)); + Assert.assertFalse("Sprite instance is strictly not a MovieClip", strictIs(s, MovieClip)); + } + + } +} \ No newline at end of file
as3/as3-utils
e832b5fc07b23ca623fe7a5bbb001c8d843a995b
using uint instead of number for iterator
diff --git a/src/utils/validation/isValidCreditCardNumber.as b/src/utils/validation/isValidCreditCardNumber.as index ba08c09..f384690 100644 --- a/src/utils/validation/isValidCreditCardNumber.as +++ b/src/utils/validation/isValidCreditCardNumber.as @@ -1,74 +1,74 @@ package utils.validation { import utils.string.toNumeric; /** * Validate a credit card number as much as possible before submitting for approval. * @param strNumber credit card number as string * @example <listing version="3.0"> * var isValidNumber:Boolean = CreditCardValidator.isValidNumber("1234567890123456"); * </listing> */ public function isValidCreditCardNumber(strNumber:String):Boolean { var mod10:Function = function mod10(strNumber:String):Boolean { // Seperate each number into it's own index in an array. var aNumbers:Array = strNumber.split(""); // Hold the sums of some calculations that will be made shortly. var nSum_1:Number = 0; var nSum_2:Number = 0; var nSum_Total:Number = 0; // Check to see if the length of the card number is odd or even. This will // be used to determine which indicies are doubled before being summed up. var nParity:Number = aNumbers.length % 2; // Loop through the card numbers. - for (var i:Number = 0; i < aNumbers.length; i++) + for (var i:uint = 0; i < aNumbers.length; i++) { // Type cast each digit to a number. var num:uint = uint(aNumbers[i]); aNumbers[i] = num; // Compare the parity of the index to the parity of the card number length // to determine how the value of the current index is handled. if (i % 2 == nParity) { // Double each number. aNumbers[i] *= 2; // If the resulting value is greater than '9', subtract '9' from it. aNumbers[i] = aNumbers[i] > 9 ? aNumbers[i] - 9 : aNumbers[i]; // Add each value together. nSum_1 += aNumbers[i]; } else { // Add each value together. nSum_2 += aNumbers[i]; } } // Find the total sum of the two groups. nSum_Total = nSum_1 + nSum_2; // If the sum is divisible by '10', the card number is valid. return (nSum_Total % 10 == 0); } const MINIMUM_CARD_LENGTH:int = 13; const MAXIMUM_CARD_LENGTH:int = 16; var ccNumber:String = toNumeric(strNumber); if (ccNumber.length > 0 && !isNaN(ccNumber as Number) && (ccNumber.length >= MINIMUM_CARD_LENGTH && ccNumber.length <= MAXIMUM_CARD_LENGTH)) { return mod10(ccNumber); } return false; } } \ No newline at end of file
as3/as3-utils
04b8b7ac6d163e5119e4b1acd5e5b8943d7a2b1c
passing tests for isValidCreditCardNumber, isValidEmail, isValidExpirationData, and isValidPhoneNumber
diff --git a/src/utils/validation/isValidCreditCardNumber.as b/src/utils/validation/isValidCreditCardNumber.as index ecad1a9..ba08c09 100644 --- a/src/utils/validation/isValidCreditCardNumber.as +++ b/src/utils/validation/isValidCreditCardNumber.as @@ -1,71 +1,74 @@ package utils.validation { import utils.string.toNumeric; /** * Validate a credit card number as much as possible before submitting for approval. * @param strNumber credit card number as string * @example <listing version="3.0"> * var isValidNumber:Boolean = CreditCardValidator.isValidNumber("1234567890123456"); * </listing> */ public function isValidCreditCardNumber(strNumber:String):Boolean { var mod10:Function = function mod10(strNumber:String):Boolean { // Seperate each number into it's own index in an array. var aNumbers:Array = strNumber.split(""); // Hold the sums of some calculations that will be made shortly. var nSum_1:Number = 0; var nSum_2:Number = 0; var nSum_Total:Number = 0; // Check to see if the length of the card number is odd or even. This will // be used to determine which indicies are doubled before being summed up. var nParity:Number = aNumbers.length % 2; // Loop through the card numbers. for (var i:Number = 0; i < aNumbers.length; i++) { // Type cast each digit to a number. - aNumbers[i] = Number(aNumbers[i]); + + var num:uint = uint(aNumbers[i]); + + aNumbers[i] = num; // Compare the parity of the index to the parity of the card number length // to determine how the value of the current index is handled. if (i % 2 == nParity) { // Double each number. aNumbers[i] *= 2; // If the resulting value is greater than '9', subtract '9' from it. aNumbers[i] = aNumbers[i] > 9 ? aNumbers[i] - 9 : aNumbers[i]; // Add each value together. nSum_1 += aNumbers[i]; } else { // Add each value together. nSum_2 += aNumbers[i]; } } // Find the total sum of the two groups. nSum_Total = nSum_1 + nSum_2; // If the sum is divisible by '10', the card number is valid. return (nSum_Total % 10 == 0); } const MINIMUM_CARD_LENGTH:int = 13; const MAXIMUM_CARD_LENGTH:int = 16; var ccNumber:String = toNumeric(strNumber); if (ccNumber.length > 0 && !isNaN(ccNumber as Number) && (ccNumber.length >= MINIMUM_CARD_LENGTH && ccNumber.length <= MAXIMUM_CARD_LENGTH)) { return mod10(ccNumber); } return false; } } \ No newline at end of file diff --git a/test/validation/isValidCreditCardNumberTest.as b/test/validation/isValidCreditCardNumberTest.as new file mode 100644 index 0000000..47adb86 --- /dev/null +++ b/test/validation/isValidCreditCardNumberTest.as @@ -0,0 +1,70 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/20/11 + * Time: 1:52 PM + */ +package validation { +import org.hamcrest.assertThat; +import org.hamcrest.object.equalTo; + +import utils.validation.isValidCreditCardNumber; + +public class isValidCreditCardNumberTest { + + [Test] + public function ccBelowMinimum13ShouldFail() : void { + + assertThat(isValidCreditCardNumber("1234"), equalTo(false)); + + } + + [Test] + public function ccAboveMaximum16ShouldFail() : void { + + assertThat(isValidCreditCardNumber("123413123123213421341123412423412412341232314"), equalTo(false)); + + } + + //Even CC length integrity testing + //Each number is examined + //if a number is divisible by 2 with no remainder (even) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. + //if a number is divisible by 2 with a remainder (odd) it gets added to the second group + //The first group plus the second group should be divisible by 10 with no remainder + + [Test] + public function ccEvenNumberLengthWithBadIntegrityShouldFail() : void { + + assertThat(isValidCreditCardNumber("12345678901234"), equalTo(false)); + + } + + [Test] + public function ccEvenNumberLengthWithGoodIntegrityShouldPass() : void { + + assertThat(isValidCreditCardNumber("72345678901234"), equalTo(true)); + + } + + //Odd CC length integrity testing + //Each number is examined + //if a number is divisible by 1 with no remainder (odd) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. + //if a number is divisible by 1 with a remainder (even) it gets added to the second group + //The first group plus the second group should be divisible by 10 with no remainder + + [Test] + public function ccOddNumberLengthWithBadIntegrityShouldFail() : void { + + assertThat(isValidCreditCardNumber("123456789012345"), equalTo(false)); + + } + + [Test] + public function ccOddNumberLengthWithGoodIntegrityShouldPass() : void { + + assertThat(isValidCreditCardNumber("323456789012345"), equalTo(true)); + + } + +} +} diff --git a/test/validation/isValidEmailAddress.as b/test/validation/isValidEmailAddress.as new file mode 100644 index 0000000..367508e --- /dev/null +++ b/test/validation/isValidEmailAddress.as @@ -0,0 +1,43 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/20/11 + * Time: 1:47 PM + */ +package validation { +import org.hamcrest.assertThat; +import org.hamcrest.object.equalTo; + +import utils.validation.isValidEmailAddress; + +public class isValidEmailAddress { + + [Test] + public function goodEmailPasses() : void { + + assertThat(utils.validation.isValidEmailAddress("[email protected]"), equalTo(true)) + + } + + [Test] + public function emailWithSpaceFails() : void { + + assertThat(utils.validation.isValidEmailAddress("test@ test.com"), equalTo(false)) + + } + + [Test] + public function emailWithoutAtSymbolFails() : void { + + assertThat(utils.validation.isValidEmailAddress("testtest.com"), equalTo(false)) + + } + + [Test] + public function emailWithInvalidCharacterFails() : void { + + assertThat(utils.validation.isValidEmailAddress("test@te$t.com"), equalTo(false)) + + } +} +} diff --git a/test/validation/isValidExpirationDateTest.as b/test/validation/isValidExpirationDateTest.as new file mode 100644 index 0000000..d7f0cf9 --- /dev/null +++ b/test/validation/isValidExpirationDateTest.as @@ -0,0 +1,51 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/20/11 + * Time: 1:34 PM + */ +package validation { +import org.hamcrest.assertThat; + +import org.hamcrest.object.equalTo; + +import utils.validation.isValidExpirationDate; + +public class isValidExpirationDateTest { + + [Test] + public function expirationOfNextYearShouldPass() : void { + + assertThat(isValidExpirationDate(1, new Date().getFullYear() + 1), equalTo(true)); + + } + + [Test] + public function expirationOfLastYearShouldFail() : void { + + assertThat(isValidExpirationDate(1, new Date().getFullYear() - 1), equalTo(false)); + + } + + [Test] + public function expirationOfSameYearButUpcomingMonthShouldPass() : void { + + assertThat(isValidExpirationDate(new Date().getMonth() + 1, new Date().getFullYear()), equalTo(true)); + + } + + [Test] + public function expirationOfSameYearButPastMonthShouldFail() : void { + + assertThat(isValidExpirationDate(new Date().getMonth() - 1, new Date().getFullYear()), equalTo(false)); + + } + + [Test] + public function expirationOfUpcomingYearWithMonthOfZeroShouldFail() : void { + + assertThat(isValidExpirationDate(0,new Date().getFullYear() + 1), equalTo(true)); + + } +} +} diff --git a/test/validation/isValidPhoneNumberTest.as b/test/validation/isValidPhoneNumberTest.as new file mode 100644 index 0000000..640d67c --- /dev/null +++ b/test/validation/isValidPhoneNumberTest.as @@ -0,0 +1,40 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: 5/3/11 + * Time: 5:32 PM + */ +package validation { +import org.hamcrest.assertThat; + +import org.hamcrest.object.equalTo; + +import utils.validation.isValidPhoneNumber; + +public class isValidPhoneNumberTest { + + [Test] + public function validNumberPasses() : void { + + assertThat(isValidPhoneNumber("123 456-7789"), equalTo(true)); + + } + + [Test] + public function validNumberNoDashesPasses() : void { + + assertThat(isValidPhoneNumber("123 456 7789"), equalTo(true)); + + } + + //TODO: Should this be the intended behavior? + [Test] + public function validNumberWithPrefixFails() : void { + + assertThat(isValidPhoneNumber("1 123 456-7789"), equalTo(false)); + + } + + +} +}
as3/as3-utils
daad4f3405a9a9b4bb3dc74263457de2731d84df
Edited README.md via GitHub
diff --git a/README.md b/README.md index 9b50f62..e5e8496 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,46 @@ # as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? HEAPS, too much to list here right now. Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html - number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) - Joel Hooks [@jhooks](http://twitter.com/jhooks) - Mims H. Wright [@mimshwright](http://twitter.com/mimshwright) +- Ian McLean [@ianmclean](http://twitter.com/ianmclean) - You. # Giving credit where credit is due Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. If you include your own code in the library, please be sure to add a credit for yourself in the comments or use an @author tag in the asDocs. \ No newline at end of file
as3/as3-utils
ed30e97915d791282cd492fc8be6ee2517100a99
spark.primitives.Graphic leftover in duplicateDisplayObject()
diff --git a/src/utils/display/duplicateDisplayObject.as b/src/utils/display/duplicateDisplayObject.as index 73f0680..53a9e68 100644 --- a/src/utils/display/duplicateDisplayObject.as +++ b/src/utils/display/duplicateDisplayObject.as @@ -1,63 +1,57 @@ -package utils.display -{ - +package utils.display { import flash.display.DisplayObject; import flash.display.Graphics; import flash.geom.Rectangle; import flash.system.Capabilities; - - import spark.primitives.Graphic; + + /** * duplicateDisplayObject * creates a duplicate of the DisplayObject passed. * similar to duplicateMovieClip in AVM1. If using Flash 9, make sure * you export for ActionScript the symbol you are duplicating - * + * * @param source the display object to duplicate * @param autoAdd if true, adds the duplicate to the display list * in which source was located * @return a duplicate instance of source - * + * * @author Trevor McCauley - www.senocular.com * @author cleaned up by Mims Wright */ - public function duplicateDisplayObject(source:DisplayObject, autoAdd:Boolean = false):DisplayObject - { + public function duplicateDisplayObject(source:DisplayObject, autoAdd:Boolean = false):DisplayObject { var sourceClass:Class = Object(source).constructor; var duplicate:DisplayObject = new sourceClass() as DisplayObject; // duplicate properties duplicate.transform = source.transform; duplicate.filters = source.filters; duplicate.cacheAsBitmap = source.cacheAsBitmap; duplicate.opaqueBackground = source.opaqueBackground; - if (source.scale9Grid) - { + if(source.scale9Grid) { var rect:Rectangle = source.scale9Grid; // version check for scale9Grid bug - if (Capabilities.version.split(" ")[1] == "9,0,16,0") - { + if(Capabilities.version.split(" ")[1] == "9,0,16,0") { // Flash 9 bug where returned scale9Grid as twips - rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20; + rect.x /= 20,rect.y /= 20,rect.width /= 20,rect.height /= 20; } duplicate.scale9Grid = rect; } // todo: needs test - if ("graphics" in source) { + if("graphics" in source) { var graphics:Graphics = Graphics(source["graphics"]); Graphics(duplicate["graphics"]).copyFrom(graphics); } // add to target parent's display list // if autoAdd was provided as true - if (autoAdd && source.parent) - { + if(autoAdd && source.parent) { source.parent.addChild(duplicate); } return duplicate; } -} \ No newline at end of file +}
as3/as3-utils
e224b21c6cf36435dac69e3eea021df99d9cb589
Minor spell checking in my contributions
diff --git a/src/utils/display/traceChildren.as b/src/utils/display/traceChildren.as index c82628d..3429be1 100644 --- a/src/utils/display/traceChildren.as +++ b/src/utils/display/traceChildren.as @@ -1,27 +1,27 @@ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * trace() children of the DisplayObjectContainer. * @param container DisplayObjectContainer to get children of - * @param indentLevel Indetnation level (default 0) + * @param indentLevel Indentation level (default 0) * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function traceChildren(container:DisplayObjectContainer, indentLevel:int = 0):void { for(var i:int = 0; i < container.numChildren; i++) { var thisChild:DisplayObject = container.getChildAt(i); var output:String = ""; for(var j:int = 0; j < indentLevel; j++) output += " "; output += "+ " + thisChild.name + " = " + String(thisChild); trace(output); if(thisChild is DisplayObjectContainer) traceChildren(DisplayObjectContainer(thisChild), indentLevel + 1); } } } diff --git a/src/utils/geom/simplifyAngle.as b/src/utils/geom/simplifyAngle.as index 178e2bf..df9925b 100644 --- a/src/utils/geom/simplifyAngle.as +++ b/src/utils/geom/simplifyAngle.as @@ -1,21 +1,21 @@ package utils.geom { /** * Simplifies the supplied angle to its simplest representation. * Example code: * <pre> * var simpAngle:Number = simplifyAngle(725); // returns 5 * var simpAngle2:Number = simplifyAngle(-725); // returns -5 * </pre> - * @param value Angle to simplify in degrees + * @param angle Angle to simplify in degrees * @return Supplied angle simplified * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function simplifyAngle(angle:Number):Number { var _rotations:Number = Math.floor(angle / 360); return (angle >= 0) ? angle - (360 * _rotations) : angle + (360 * _rotations); } } diff --git a/src/utils/js/callJSFunction.as b/src/utils/js/callJSFunction.as index f57086b..e527844 100644 --- a/src/utils/js/callJSFunction.as +++ b/src/utils/js/callJSFunction.as @@ -1,40 +1,40 @@ package utils.js { import flash.external.ExternalInterface; /** * Call a JS function. * @param func Name of the function to be called * @param arg1 Argument 1 * @param arg2 Argument 2 * @param arg3 Argument 3 * @param arg4 Argument 4 * @throws Error if empty function name supplied - * @throws Error if SecurityError occured - * @throws Error if Error occured + * @throws Error if SecurityError occurred + * @throws Error if Error occurred * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function callJSFunction(func:String, arg1:* = null, arg2:* = null, arg3:* = null, arg4:* = null):void { if(func == "") { throw new Error("A valid function argument must be supplied"); } // track avea if a type is supplied if(ExternalInterface.available) { try { ExternalInterface.call(func, arg1, arg2, arg3, arg4); } catch(error:SecurityError) { throw new Error(func + " request failed. A SecurityError occurred: " + error.message + "\n"); } catch (error:Error) { throw new Error(func + " request failed. An Error occurred: " + error.message + "\n"); } } else { throw new Error(func + " request Failed. External interface is not available for this container. If you're trying to use it locally, try using it through an HTTP address."); } } }
as3/as3-utils
333d008851de397abb68e291ff4e15a6f5a65bc7
randomRangeSet() now uses non-deprecated randomIntegerWithinRange()
diff --git a/src/utils/range/randomRangeSet.as b/src/utils/range/randomRangeSet.as index f0825b4..89775ef 100644 --- a/src/utils/range/randomRangeSet.as +++ b/src/utils/range/randomRangeSet.as @@ -1,35 +1,32 @@ -package utils.range -{ +package utils.range { + import utils.number.randomIntegerWithinRange; + + + /** * Returns a set of random numbers inside a specific range (unique numbers is optional) */ - public function randomRangeSet(min:Number, max:Number, count:Number, unique:Boolean):Array - { + public function randomRangeSet(min:Number, max:Number, count:Number, unique:Boolean):Array { var rnds:Array = new Array(); - if (unique && count <= max - min + 1) - { + if(unique && count <= max - min + 1) { //unique - create num range array var nums:Array = new Array(); - for (var i:Number = min; i <= max; i++) - { + for(var i:Number = min; i <= max; i++) { nums.push(i); } - for (var j:Number = 1; j <= count; j++) - { + for(var j:Number = 1; j <= count; j++) { // random number var rn:Number = Math.floor(Math.random() * nums.length); rnds.push(nums[rn]); nums.splice(rn, 1); } } - else - { + else { //non unique - for (var k:Number = 1; k <= count; k++) - { - rnds.push(randomRangeInt(min, max)); + for(var k:Number = 1; k <= count; k++) { + rnds.push(randomIntegerWithinRange(min, max)); } } return rnds; } -} \ No newline at end of file +}
as3/as3-utils
977bd848c72aa2f88d27c2ec8ef660909e978636
Some functions were duplicated, so I moved them to deprecated (getURL, randomBoolean, randomRangeFloat, randomRangeInt)
diff --git a/src/utils/net/getURL.as b/src/deprecated/getURL.as similarity index 54% rename from src/utils/net/getURL.as rename to src/deprecated/getURL.as index 06eeefa..364a4a2 100644 --- a/src/utils/net/getURL.as +++ b/src/deprecated/getURL.as @@ -1,23 +1,25 @@ -package utils.net -{ +package deprecated { import flash.net.URLRequest; import flash.net.navigateToURL; - + + + + [Deprecated(replacement="utils.location.openURL")] /** - * getURL for ActionScript 3.0. Similar + * getURL for ActionScript 3.0. Similar * to getURL of ActionScript 2.0 in simplicity * and ease. Errors are suppressed and traced * to the output window. - * + * * @author Trevor McCauley - www.senocular.com - */ - public function getURL(url:String, target:String = null):void { - + */ public function getURL(url:String, target:String = null):void { + try { navigateToURL(new URLRequest(url), target); - }catch(error:Error){ - trace("[getURL] "+error); } - + catch(error:Error) { + trace("[getURL] " + error); + } + } -} \ No newline at end of file +} diff --git a/src/utils/number/randomBoolean.as b/src/deprecated/randomBoolean.as similarity index 78% rename from src/utils/number/randomBoolean.as rename to src/deprecated/randomBoolean.as index 5f062e1..dd80680 100644 --- a/src/utils/number/randomBoolean.as +++ b/src/deprecated/randomBoolean.as @@ -1,24 +1,23 @@ -package utils.number { - +package deprecated { + [Deprecated(replacement="utils.boolean.randomChance")] /** * Returns a Boolean. * Example code: * <pre> * RandomUtils.boolean(); // returns true or false (50% chance of true) * </pre> * Another example code: * <pre> * RandomUtils.boolean(0.8); // returns true or false (80% chance of true) * </pre> * @param chance Chance Number (0-1) * @return Float Number between min-max exclusive. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson - */ - public function randomBoolean(chance:Number = 0.5):Boolean { + */ public function randomBoolean(chance:Number = 0.5):Boolean { return(Math.random() < chance); } } diff --git a/src/deprecated/randomRangeFloat.as b/src/deprecated/randomRangeFloat.as new file mode 100644 index 0000000..6edd685 --- /dev/null +++ b/src/deprecated/randomRangeFloat.as @@ -0,0 +1,10 @@ +package deprecated { + [Deprecated(replacement="utils.number.randomWithinRange")] + + + /** + * Returns a random float number within a given range + */ public function randomRangeFloat(min:Number, max:Number):Number { + return Math.random() * (max - min) + min; + } +} diff --git a/src/deprecated/randomRangeInt.as b/src/deprecated/randomRangeInt.as new file mode 100644 index 0000000..bdff0e6 --- /dev/null +++ b/src/deprecated/randomRangeInt.as @@ -0,0 +1,11 @@ +package deprecated { + [Deprecated(replacement="utils.number.randomIntegerWithinRange")] + + + + /** + * Returns a random int number within a given range + */ public function randomRangeInt(min:Number, max:Number):Number { + return Math.floor(Math.random() * (max - min + 1) + min); + } +} diff --git a/src/utils/range/randomRangeFloat.as b/src/utils/range/randomRangeFloat.as deleted file mode 100644 index 5dcde9b..0000000 --- a/src/utils/range/randomRangeFloat.as +++ /dev/null @@ -1,10 +0,0 @@ -package utils.range -{ - /** - * Returns a random float number within a given range - */ - public function randomRangeFloat(min:Number, max:Number):Number - { - return Math.random() * (max - min) + min; - } -} \ No newline at end of file diff --git a/src/utils/range/randomRangeInt.as b/src/utils/range/randomRangeInt.as deleted file mode 100644 index 078aa98..0000000 --- a/src/utils/range/randomRangeInt.as +++ /dev/null @@ -1,10 +0,0 @@ -package utils.range -{ - /** - * Returns a random int number within a given range - */ - public function randomRangeInt(min:Number, max:Number):Number - { - return Math.floor(Math.random() * (max - min + 1) + min); - } -} \ No newline at end of file
as3/as3-utils
355b54366369db85c759c2439761988ef154f446
Some utils.location functions belong to utils.capabilities (isAirApplication, isIDE, isPlugin, isStandAlone, isWeb)
diff --git a/src/utils/location/isAirApplication.as b/src/utils/capabilities/isAirApplication.as similarity index 92% rename from src/utils/location/isAirApplication.as rename to src/utils/capabilities/isAirApplication.as index c6b6371..ebdcabc 100644 --- a/src/utils/location/isAirApplication.as +++ b/src/utils/capabilities/isAirApplication.as @@ -1,16 +1,16 @@ -package utils.location { +package utils.capabilities { import flash.system.Capabilities; /** * Determines if the runtime environment is an Air application. * @return true if the runtime environment is an Air application * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isAirApplication():Boolean { return Capabilities.playerType == "Desktop"; } } diff --git a/src/utils/location/isIDE.as b/src/utils/capabilities/isIDE.as similarity index 92% rename from src/utils/location/isIDE.as rename to src/utils/capabilities/isIDE.as index 06a83a6..fec8dda 100644 --- a/src/utils/location/isIDE.as +++ b/src/utils/capabilities/isIDE.as @@ -1,16 +1,16 @@ -package utils.location { +package utils.capabilities { import flash.system.Capabilities; /** * Determines if the SWF is running in the IDE. * @return true if SWF is running in the Flash Player version used by the external player or test movie mode * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isIDE():Boolean { return Capabilities.playerType == "External"; } } diff --git a/src/utils/location/isPlugin.as b/src/utils/capabilities/isPlugin.as similarity index 93% rename from src/utils/location/isPlugin.as rename to src/utils/capabilities/isPlugin.as index 8f3c03a..0228847 100644 --- a/src/utils/location/isPlugin.as +++ b/src/utils/capabilities/isPlugin.as @@ -1,16 +1,16 @@ -package utils.location { +package utils.capabilities { import flash.system.Capabilities; /** * Determines if the SWF is running in a browser plug-in. * @return true if SWF is running in the Flash Player browser plug-in * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isPlugin():Boolean { return Capabilities.playerType == "PlugIn" || Capabilities.playerType == "ActiveX"; } } diff --git a/src/utils/location/isStandAlone.as b/src/utils/capabilities/isStandAlone.as similarity index 92% rename from src/utils/location/isStandAlone.as rename to src/utils/capabilities/isStandAlone.as index 6c3ffc2..48fd293 100644 --- a/src/utils/location/isStandAlone.as +++ b/src/utils/capabilities/isStandAlone.as @@ -1,16 +1,16 @@ -package utils.location { +package utils.capabilities { import flash.system.Capabilities; /** * Determines if the SWF is running in the StandAlone player. * @return true if SWF is running in the Flash StandAlone Player * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isStandAlone():Boolean { return Capabilities.playerType == "StandAlone"; } } diff --git a/src/utils/location/isWeb.as b/src/utils/capabilities/isWeb.as similarity index 94% rename from src/utils/location/isWeb.as rename to src/utils/capabilities/isWeb.as index 1430c3e..a289fee 100644 --- a/src/utils/location/isWeb.as +++ b/src/utils/capabilities/isWeb.as @@ -1,21 +1,21 @@ -package utils.location { +package utils.capabilities { import flash.display.DisplayObject; /** * Determines if the SWF is being served on the internet. * Example code: * <pre> * trace(isWeb(_root)); * </pre> * @param location DisplayObject to get location of * @return true if SWF is being served on the internet * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isWeb(location:DisplayObject):Boolean { return location.loaderInfo.url.substr(0, 4) == "http"; } } diff --git a/src/utils/location/getLocationName.as b/src/utils/location/getLocationName.as index c62965a..87e88bd 100644 --- a/src/utils/location/getLocationName.as +++ b/src/utils/location/getLocationName.as @@ -1,50 +1,53 @@ package utils.location { import flash.external.ExternalInterface; + import utils.capabilities.isStandAlone; + /** * Return current location name. * @return Current location name * @author Aaron Clinger * @author Shane McCartney * @author David Nelson * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function getLocationName():String { var out:String; var browserAgent:String; if(isStandAlone()) { out = locationNames.STANDALONE_PLAYER; } else { if(ExternalInterface.available) { // uses external interface to reach out to browser and grab browser useragent info. browserAgent = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); // determines brand of browser using a find index. If not found indexOf returns (-1). // noinspection IfStatementWithTooManyBranchesJS if(browserAgent != null && browserAgent.indexOf("Firefox") >= 0) { out = locationNames.BROWSER_FIREFOX; } else if(browserAgent != null && browserAgent.indexOf("Safari") >= 0) { out = locationNames.BROWSER_SAFARI; } else if(browserAgent != null && browserAgent.indexOf("MSIE") >= 0) { out = locationNames.BROWSER_IE; } else if(browserAgent != null && browserAgent.indexOf("Opera") >= 0) { out = locationNames.BROWSER_OPERA; - } else { + } + else { out = locationNames.BROWSER_UNDEFINED; } } else { // standalone player out = locationNames.BROWSER_UNDEFINED; } } return out; } } diff --git a/src/utils/location/openURL.as b/src/utils/location/openURL.as index 3863b0c..edda01b 100644 --- a/src/utils/location/openURL.as +++ b/src/utils/location/openURL.as @@ -1,34 +1,36 @@ package utils.location { import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; + import utils.capabilities.isIDE; + /** * Simlifies navigateToURL by allowing you to either use a String or an URLRequest * reference to the URL. This method also helps prevent pop-up blocking by trying to use * openWindow() before calling navigateToURL. * @param request A String or an URLRequest reference to the URL you wish to open/navigate to * @param window Browser window or HTML frame in which to display the URL indicated by the request parameter * @throws Error if you pass a value type other than a String or URLRequest to parameter request. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function openURL(request:*, window:String = "_self" /* windowNames.WINDOW_SELF */):void { var r:* = request; if(r is String) { r = new URLRequest(r); } else if(!(r is URLRequest)) { throw new Error("request"); } if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE() && request._data == null) { if(openWindow(r.url, window)) return } navigateToURL(r, window); } }
as3/as3-utils
124218720aabab9471548f9513da569955fdf9b7
Modified readme
diff --git a/README.md b/README.md index 9b50f62..637b5e7 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,47 @@ # as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? HEAPS, too much to list here right now. Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html - number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? +Check out the [contribution guidelines](https://github.com/as3/as3-utils/blob/master/Contribution%20Guidelines.md). + Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) - Joel Hooks [@jhooks](http://twitter.com/jhooks) - Mims H. Wright [@mimshwright](http://twitter.com/mimshwright) -- You. +- [You?](https://github.com/as3/as3-utils/blob/master/Contribution%20Guidelines.md) # Giving credit where credit is due Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. If you include your own code in the library, please be sure to add a credit for yourself in the comments or use an @author tag in the asDocs. \ No newline at end of file
as3/as3-utils
3417bd71cc7beeb74fd859b9ff2df070c9c59da3
unused import
diff --git a/test/utils/date/calendar/CalendarTests.as b/test/utils/date/calendar/CalendarTests.as index e1ce11b..dd667f2 100644 --- a/test/utils/date/calendar/CalendarTests.as +++ b/test/utils/date/calendar/CalendarTests.as @@ -1,28 +1,27 @@ /** * User: John Lindquist * Date: 3/16/11 * Time: 11:14 AM */ package utils.date.calendar { - import org.flexunit.asserts.assertEquals; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.date.Calendar; public class CalendarTests { [Test] public function now_should_be_the_current_time():void { var calendar:Calendar = new Calendar(); assertThat(calendar.now.toString(), equalTo(new Date().toString())); } } } \ No newline at end of file
as3/as3-utils
4e3afa9a5ae358fcc2b99a63e9414bfffc62c70a
needed return type
diff --git a/test/utils/xml/GetNextSiblingTest.as b/test/utils/xml/GetNextSiblingTest.as index c53bf0c..7c864f1 100644 --- a/test/utils/xml/GetNextSiblingTest.as +++ b/test/utils/xml/GetNextSiblingTest.as @@ -1,29 +1,29 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 2:28 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class GetNextSiblingTest { [Test] - public function requestedIndexShouldReturnNextNode() { + public function requestedIndexShouldReturnNextNode() : void { var x:XML = <root> <stuff>value1</stuff> <stuff>value2</stuff> <stuff>value3</stuff> </root> var sibling:* = getNextSibling(x.stuff[1]); assertThat(sibling, equalTo(x.stuff[2])); } } } diff --git a/test/utils/xml/GetPreviousSiblingTest.as b/test/utils/xml/GetPreviousSiblingTest.as index 5c2d8bf..8bbe4f6 100644 --- a/test/utils/xml/GetPreviousSiblingTest.as +++ b/test/utils/xml/GetPreviousSiblingTest.as @@ -1,29 +1,29 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 2:08 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class GetPreviousSiblingTest { [Test] - public function callShouldReturnPreviousNode() { + public function callShouldReturnPreviousNode() : void { var x:XML = <root> <stuff>value1</stuff> <stuff>value2</stuff> <stuff>value3</stuff> </root> var sibling:* = getPreviousSibling(x.stuff[2]); assertThat(sibling, equalTo(x.stuff[1])); } } } diff --git a/test/utils/xml/GetSiblingByIndexTest.as b/test/utils/xml/GetSiblingByIndexTest.as index 5b98d78..1ab5a48 100644 --- a/test/utils/xml/GetSiblingByIndexTest.as +++ b/test/utils/xml/GetSiblingByIndexTest.as @@ -1,30 +1,30 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 12:04 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class GetSiblingByIndexTest { [Test] - public function requestedIndexShouldReturnProperNode() { + public function requestedIndexShouldReturnProperNode() : void { var x:XML = <root> <stuff>value1</stuff> <stuff>value2</stuff> <stuff>value3</stuff> </root> var sibling:* = getSiblingByIndex(x.stuff[2], -1); assertThat(sibling, equalTo(x.stuff[1])) } } } diff --git a/test/utils/xml/isValidXMLTest.as b/test/utils/xml/isValidXMLTest.as index 4790fe7..c074dfa 100644 --- a/test/utils/xml/isValidXMLTest.as +++ b/test/utils/xml/isValidXMLTest.as @@ -1,32 +1,32 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/2/11 * Time: 4:40 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class isValidXMLTest { [Test] - public function validXMLShouldReturnTrue() { + public function validXMLShouldReturnTrue() : void { var s:String = "<goodxml></goodxml>"; assertThat(isValidXML(s), equalTo(true)) } [Test] - public function invalidXMLShouldReturnFalse() { + public function invalidXMLShouldReturnFalse() : void { var s:String = "<badXml></badXmL>"; assertThat(isValidXML(s), equalTo(false)) } } }
as3/as3-utils
8db34e86202ee880b3287c2e08ba8c4458590203
switching comparison to use hamcrest hasProperties matcher. hasAnyProperties only requires that an object has a single property to pass - this wasn't verifying the merge.
diff --git a/test/utils/object/MergeTest.as b/test/utils/object/MergeTest.as index ac5c237..bd971c7 100644 --- a/test/utils/object/MergeTest.as +++ b/test/utils/object/MergeTest.as @@ -1,16 +1,17 @@ package utils.object { import org.hamcrest.assertThat; +import org.hamcrest.object.hasProperties; - public class MergeTest +public class MergeTest { [Test] public function copiesEnumerablePropertiesAndValuesFromSourceToTarget():void { var source:Object = { a: 1, d: 4 }; var target:Object = { a: 0, b: 2, c: 3 } - assertThat(merge(target, source), hasAnyProperties({ a: 1, b: 2, c: 3, d: 4 })); + assertThat(merge(target, source), hasProperties({ a: 1, b: 2, c: 3, d: 4 })); } } } \ No newline at end of file
as3/as3-utils
7110f1b78827b2439ff2104cf8f8c84432d233e1
PolarToCartesianCoordinatesTest fix and a fix to CalendarTests that was causing errors.
diff --git a/src/utils/geom/polarToCartesianCoordinates.as b/src/utils/geom/polarToCartesianCoordinates.as index 9b5b9c0..99b34e9 100644 --- a/src/utils/geom/polarToCartesianCoordinates.as +++ b/src/utils/geom/polarToCartesianCoordinates.as @@ -1,25 +1,26 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 1:00:51 PM */ package utils.geom { import flash.geom.Point; /** - Converts polar coordinates to cartesian coordinates. - - @param r: The r value of the polar coordinate. - @param q: The q value of the polar coordinate in degrees. + * Converts polar coordinates to cartesian coordinates. + * @param r The r value of the polar coordinate. + * @param q The q value of the polar coordinate in degrees. */ public function polarToCartesianCoordinates(r:Number, q:Number) : Point { - var x:Number = r * Math.cos(q); - var y:Number = r * Math.sin(q); + var asRadian:Number = q * Math.PI/180 + + var x:Number = r * Math.cos(asRadian); + var y:Number = r * Math.sin(asRadian); return new Point(x,y) } } \ No newline at end of file diff --git a/test/utils/date/calendar/CalendarTests.as b/test/utils/date/calendar/CalendarTests.as index 8bad55d..e1ce11b 100644 --- a/test/utils/date/calendar/CalendarTests.as +++ b/test/utils/date/calendar/CalendarTests.as @@ -1,24 +1,28 @@ /** * User: John Lindquist * Date: 3/16/11 * Time: 11:14 AM */ package utils.date.calendar { import org.flexunit.asserts.assertEquals; - public class CalendarTests +import org.hamcrest.assertThat; + +import org.hamcrest.object.equalTo; + +import utils.date.Calendar; + +public class CalendarTests { [Test] public function now_should_be_the_current_time():void { - assertEquals(now.toString(), new Date().toString()); + var calendar:Calendar = new Calendar(); + + assertThat(calendar.now.toString(), equalTo(new Date().toString())); } - [Test] - public function today_should_be():void - { - assertEquals(today.toString(), now.toString()); - } + } } \ No newline at end of file diff --git a/test/utils/geom/PolarToCartesianCoordinatesTest.as b/test/utils/geom/PolarToCartesianCoordinatesTest.as index f66d4e7..c6674e0 100644 --- a/test/utils/geom/PolarToCartesianCoordinatesTest.as +++ b/test/utils/geom/PolarToCartesianCoordinatesTest.as @@ -1,35 +1,34 @@ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 11:50:50 AM */ package utils.geom { import flash.geom.Point; import org.flexunit.asserts.assertTrue; +import org.hamcrest.assertThat; + +import org.hamcrest.object.equalTo; + import utils.geom.cartesianToPolarCoordinates; import utils.geom.polarToCartesianCoordinates; public class PolarToCartesianCoordinatesTest - { - - [Before] - public function setup():void - { - - } - - [Test] - public function PolarToCartesianCoordinatesReturnsProperCoords():void - { +{ - var cartesianPoint:Point = polarToCartesianCoordinates(5, 53.13010235415598); + [Test] + public function PolarToCartesianCoordinatesReturnsProperCoords():void + { + //R is 12, theta is 195 degrees + var cartesianPoint:Point = polarToCartesianCoordinates(12, 195); - assertTrue(cartesianPoint.x == 3, cartesianPoint.y == 4); + assertThat(cartesianPoint.x, equalTo(-11.59110991546882)); + assertThat(cartesianPoint.y, equalTo(-3.1058285412302444)); - } + } - } +} } \ No newline at end of file
as3/as3-utils
f7e76e0fe29d1854c5e3750761b94926626693ad
rewrote numberToString().
diff --git a/src/utils/string/numberToString.as b/src/utils/string/numberToString.as index 5855b8c..9084d95 100644 --- a/src/utils/string/numberToString.as +++ b/src/utils/string/numberToString.as @@ -1,157 +1,171 @@ package utils.string { /** * Converts a number to its text equivelant * * @params n The number to convert * @returns String equivelant of the number * @playerversion Flash 10.0 * @author Mims H. Wright */ - public function numberToString(n:uint):String { - var str:String; // str will hold the final outcome + public function numberToString(n:Number):String { var output:Vector.<String> = new Vector.<String>(); // output will temporarily hold the strings that make up str - var digits:Vector.<String> = new Vector.<String>(); // digit is an array of digits based on the number n - var negative:Boolean = false; // used for removing minus sign. + var isNegative:Boolean = false; // used for removing minus sign. + var integers:Number; + var decimals:Number; + // check for NaN + if (isNaN(n)) { return N.NAN; } // check for zero - if (n == 0) { return N._0; } // todo: tidy + if (n == 0) { return N._0; } // check for negatives if (n < 0) { - negative = true; + isNegative = true; n *= -1; } - digits = Vector.<String>(n.toString().split("")); - // reverse the array so that each order of ten can be represented by - // an element of the periods array. - digits.reverse(); - var max:Number = digits.length; - - // for each digit in n - var magnitude:int = 0; - for (;magnitude < max; magnitude+=1) { - var pos:int = magnitude; + // solve for decimals + var decimalPointIndex:int = n.toString().indexOf("."); + if (decimalPointIndex > -1) { + digits = Vector.<String> (n.toString().substr(decimalPointIndex + 1).split("")); + digits.reverse(); - var digitInt:int = int(digits[pos]); - var periodForThisMagnitude:Vector.<String> = N.periods[magnitude]; -// var textForThisDigit:String = periodForThisMagnitude[digitInt] - // push the text equivelant to the output -// output.push(textForThisDigit); - output.push(N.periods[magnitude][digits[pos]]); + var i:int = 0; + var digit:int; + for (; i < digits.length; i += 1) { + digit = int(digits[i]); + if (digit == 0) { + output.push(N._0 + " "); + } else { + output.push(N._1to9[digit]); + } + } + output.push(N.decimal); + } + + // solve for integers + integers = Math.floor(n); + var period:int = 0; + var digits:Vector.<String> = Vector.<String>(integers.toString().split("")).reverse(); + var hundreds:int; + var tens:int; + var ones:int; + var next3:String; + while (digits.length > 0) { + // grab the next three digits and analyze them. + next3 = digits.slice(0,3).join(""); - // anytime ten is written it's a special case. - // the second magnitude and every 3 magnitudes after are special - var s:Number = magnitude % 3; + if (next3 != "000") { + output.push(N.periods[period]); + } - // if this is a special case and output for special (tens) place is ten - if ((s == 1) && (output[magnitude] == N.periods[1][1])) { - // delete the value for the ones place - output[magnitude] = ""; - // choose a new value for tens using a special case - var newTxt:String - switch (int(digits[magnitude-1])) { - case (0) : newTxt = N._10; break; - case (1) : newTxt = N._11; break; - case (2) : newTxt = N._12; break; - case (3) : newTxt = N._13; break; - case (4) : newTxt = N._14; break; - case (5) : newTxt = N._15; break; - case (6) : newTxt = N._16; break; - case (7) : newTxt = N._17; break; - case (8) : newTxt = N._18; break; - case (9) : newTxt = N._19; break; + ones = int(digits[0]); + + try { tens = int(digits[1]); } + catch (e:RangeError) { tens = NaN;} + + try { hundreds = int(digits[2]); } + catch (e:RangeError) { hundreds = NaN; } + + if (!isNaN(tens)) { + if (tens == 1) { + output.push(N._10to19[ones]); + } else { + output.push(N._1to9[ones]); + output.push(N._10to90[tens]); } - // replace the word 'ten' with the new text. - var spc:Number = output[magnitude-1].indexOf(" "); - output[magnitude-1] = newTxt + output[magnitude-1].substr(spc + 1); + } else { + output.push(N._1to9[ones]); } - } + if (!isNaN(hundreds)) { + output.push(N._100to900[hundreds]); + } + + // advance the period counter + period++; + // remove those three digits from the array of digits + digits.splice(0, 3); + } + - if (negative == true) { - output.push("negative "); + if (isNegative == true) { + output.push(N.negative); n *= -1; } // reverse the output so that it will look correct output.reverse(); // save the output to the string - str = output.join(""); + var str:String = output.join(""); + // remove any trailing spaces. + if (str.charAt(str.length-1) == " ") { + str = str.substr(0, str.length-1); + } return str; } } internal class N { + public static const NAN:String = "not a number"; + public static const decimal:String = "point "; + public static const negative:String = "negative "; + public static const _0:String = "zero"; public static const _1:String = "one "; public static const _2:String = "two "; public static const _3:String = "three "; public static const _4:String = "four "; public static const _5:String = "five "; public static const _6:String = "six "; public static const _7:String = "seven "; public static const _8:String = "eight "; public static const _9:String = "nine "; public static const _10:String = "ten "; public static const _11:String = "eleven "; public static const _12:String = "twelve "; public static const _13:String = "thirteen "; public static const _14:String = "fourteen "; public static const _15:String = "fifteen "; public static const _16:String = "sixteen "; public static const _17:String = "seventeen "; public static const _18:String = "eighteen "; public static const _19:String = "nineteen "; public static const _20:String = "twenty "; public static const _30:String = "thirty "; public static const _40:String = "fourty "; public static const _50:String = "fifty "; public static const _60:String = "sixty "; public static const _70:String = "seventy "; public static const _80:String = "eighty "; public static const _90:String = "ninety "; public static const _100:String = "hundred "; public static const _1000:String = "thousand "; public static const _1000000:String = "million "; public static const _1000000000:String = "billion "; public static const _1000000000000:String = "trillion "; public static const _1000000000000000:String = "quadrillion "; + public static const _1000000000000000000:String = "quintillion "; + public static const _1000000000000000000000:String = "sextillion "; + public static const _1000000000000000000000000:String = "septillion "; + public static const _1000000000000000000000000000:String = "octillion "; public static const _1to9:Vector.<String> = Vector.<String>(["",_1,_2,_3,_4,_5,_6,_7,_8,_9]); + public static const _10to19:Vector.<String> = Vector.<String>([_10,_11,_12,_13,_14,_15,_16,_17,_18,_19]); public static const _10to90:Vector.<String> = Vector.<String>(["",_10,_20,_30,_40,_50,_60,_70,_80,_90]); public static const _100to900:Vector.<String> = Vector.<String>(["",_1 + _100, _2 + _100, _3 + _100, _4 + _100, _5 + _100, _6 + _100, _7 + _100, _8 + _100, _9 + _100]); - /** - * Period generator. Creates arrays of periods of numeric text equivelants. ie. 1thousand, 10thousand, 100thousand - * - * @param counter - the name of the period (ie 'billion') - * @returns array - an array of three arrays that represent the period, to be appended to the master period - */ - private static function createPeriod (counter:String):Vector.<Vector.<String>> { - var period:Vector.<Vector.<String>> = Vector.<Vector.<String>> ([ - Vector.<String>(["",_1 + counter, _2 + counter, _3 + counter, _4 + counter, _5 + counter, _6 + counter, _7 + counter, _8 + counter, _9 + counter]), - _10to90, - _100to900 - ]); - return period; - } - - // the text equivelants of all the numbers as a multi-dimensional array - public static function get periods():Vector.<Vector.<String>> { - if (_periods == null) { - _periods = new Vector.<Vector.<String>>(); - _periods = _periods.concat( - createPeriod(_1000000000000000), // quadril - createPeriod(_1000000000000), // tril - createPeriod(_1000000000), // bil - createPeriod(_1000000), // mil - createPeriod(_1000), - createPeriod("") - ); - } - return _periods; - } - private static var _periods:Vector.<Vector.<String>>; + public static const periods:Vector.<String> = Vector.<String>( + ["", + _1000, + _1000000, + _1000000000, + _1000000000000, + _1000000000000000, + _1000000000000000000, + _1000000000000000000000, + _1000000000000000000000000, + _1000000000000000000000000000 + ]); } \ No newline at end of file diff --git a/test/utils/string/numberToStringTest.as b/test/utils/string/numberToStringTest.as new file mode 100644 index 0000000..1546429 --- /dev/null +++ b/test/utils/string/numberToStringTest.as @@ -0,0 +1,43 @@ +package utils.string +{ + import org.flexunit.asserts.*; + + public class numberToStringTest + { + [Before] + public function setup():void + { + + } + + [Test] + public function numberToStringTestPositiveNumbers():void { + assertEquals("eleven", numberToString(11)); + assertEquals("ten thousand", numberToString(10000)); + assertEquals("one billion two hundred thirty four million five hundred sixty seven thousand eight hundred ninety", numberToString(1234567890)); + } + + [Test] + public function numberToStringTestDecimalNumbers():void { + assertEquals("point one two three four five", numberToString(0.12345)); + assertEquals("one hundred one point zero zero one", numberToString(101.001)); + } + + [Test] + public function numberToStringTestNegativeNumbers():void { + assertEquals("negative one", numberToString(-1)); + } + + [Test] + public function numberToStringTestZero():void { + assertEquals("zero", numberToString(0)); + } + + [Test] + public function numberToStringTestNaN():void { + assertEquals("not a number", numberToString(NaN)); + assertEquals("not a number", numberToString(undefined)); + } + + } +} \ No newline at end of file
as3/as3-utils
dca5692826c5a2316962c5ab557b447159057ab1
Fixed a typo in a test
diff --git a/test/utils/date/calendar/CalendarTests.as b/test/utils/date/calendar/CalendarTests.as index cefda2f..0fb15ce 100644 --- a/test/utils/date/calendar/CalendarTests.as +++ b/test/utils/date/calendar/CalendarTests.as @@ -1,30 +1,30 @@ /** * User: John Lindquist * Date: 3/16/11 * Time: 11:14 AM */ package utils.date.calendar { import org.flexunit.asserts.assertEquals; import utils.date.Calendar; public class CalendarTests { [Test] public function now_should_be_the_current_time():void { assertEquals(new Calendar().now.toString(), new Date().toString()); } [Test] public function today_should_be():void { var today:Date = new Calendar().today; var now:Date = new Date(); - assertEquals(today.year, now.year); + assertEquals(today.fullYear, now.fullYear); assertEquals(today.month, now.month); assertEquals(today.date, now.date); } } } \ No newline at end of file
as3/as3-utils
212e68b84387b5cdfe4e8c237125b132d1ac8f83
rewrote calendar test
diff --git a/test/utils/date/calendar/CalendarTests.as b/test/utils/date/calendar/CalendarTests.as index 60cf962..cefda2f 100644 --- a/test/utils/date/calendar/CalendarTests.as +++ b/test/utils/date/calendar/CalendarTests.as @@ -1,26 +1,30 @@ /** * User: John Lindquist * Date: 3/16/11 * Time: 11:14 AM */ package utils.date.calendar { import org.flexunit.asserts.assertEquals; import utils.date.Calendar; public class CalendarTests { [Test] public function now_should_be_the_current_time():void { assertEquals(new Calendar().now.toString(), new Date().toString()); } [Test] public function today_should_be():void { - assertEquals(new Calendar().today.toString(), new Calendar().now.toString()); + var today:Date = new Calendar().today; + var now:Date = new Date(); + assertEquals(today.year, now.year); + assertEquals(today.month, now.month); + assertEquals(today.date, now.date); } } } \ No newline at end of file
as3/as3-utils
4288e2d07c26b5a0057a60e832f1ea4d10f0d71f
Added a note about formatting
diff --git a/Contribution Guidelines.md b/Contribution Guidelines.md index 3308099..9fa9d9b 100644 --- a/Contribution Guidelines.md +++ b/Contribution Guidelines.md @@ -1,182 +1,184 @@ #Contribution Guidelines As developers, many of us have created our own working set of classes and functions for handling the common programming tasks we come across every day. But why reinvent the wheel? **AS3-Utils** is an attempt to gather together code from all of these disparate libraries into one place in hopes of creating a reusable, well-tested, well-documented, and freely-available unified collection. If you have code in a personal library / pile of snippets that you'd like to add, please refer to these guidelines. ##What to contribute ###Flash Player Versions AS3-utils targets Flash Player 10.0+. That said, most of the snippets will work for FP 9. If there is ever a significant need for a FP9 (or 11+) version of the library, we would encourage branching or forking the project to accommodate this. Please include the minimum Flash Player version in your ASDocs if it requires FP10 or later to compile. (See Documentation below) Nothing should rely on the Flex framework (or any external libraries). ###Functions vs. Classes We've been leaning towards a *functions only* approach. This means: 1. You can type `utils.foo.bar` to explore what's available in any IDE. 1. You only have to import the single function you need instead of a class. 1. Fewer dependencies on other pieces of the library. Less reading documents in order to use the functionality you want. If you have a utility class that you'd like to add to the library, try breaking it into smaller functions before adding it. In other words, don't add `com.you.ArrayUtil`, instead add the functions within as standalone .as files. As a general guideline, contributors should always favor "snippets" over more complex object-oriented functionality. Basically, you should be able to copy/paste the function into your own class and have it "just work". Anything more complex than that would need to have an argument as to why it belongs in a utils library rather than its own library. An exception could be made for support classes that are included as internal classes but aren't accessed on their own. ####Constants Constants that can be used in a general way can be added. If there is a single constant, Pi for example, you can add it as its own standalone .as file. // PI.as package utils.number { public const PI:Number = 3.141; } If the constant value is part of an enumeration of values, you may include it in an enumeration class. // CommonColors.as package utils.color { public class CommonColors { public const RED:uint = 0xFF0000; public const GREEN:uint = 0x00FF00; public const BLUE:uint = 0x0000FF; } } ###Integrating Libraries There's a list of libraries to integrate into AS3-utils. If you'd like to pull in the utility functions from them, please do so with respect to the licenses and authors of the original code. Again, this is a snippet library rather than a collection of classes so break down the code into atomic functions with as few dependencies as possible. ###Naming - Please use self-explanatory names for your functions and avoid using abbreviations. Strive for clarity over brevity. E.g. `truncateMultilineText()`, NOT `truncMLText()` - Function names should all begin with some kind of _descriptive_ verb. E.g. - `displayDialog()` NOT `dialog()` or `doDialog()` - `getName()` or `get name()` NOT `name()` - Predicate functions, functions that return a boolean must start with `is` (as if answering a question). E.g. `isEmptyString(value:String):Boolean` NOT `empty(value:String):Boolean` - Parameter names must be descriptive. E.g. `alignLeft(objectsToAlign:Array):void` instead of `alignLeft(a:Array):void` - Variable names must be descriptive. E.g. `var targetWidth:int = target.width` instead of `var tw:int = target.width` - Please use US English for all terms. E.g. `getColor()` not `getColour()` - Remember that in common practice the package name will not be included in people's code. Therefore, to make code more readable, avoid ambiguous names for functions and classes. Rather than relying on the package name to imply what the function does, include include it in the name of the function. E.g. * `convertHexStringToUint(hexString:String):uint`, NOT `convertToUint(s:String):uint` * `XMLConstants` or better yet, `XMLNodeType`, NOT `Constants` * `utils.foo.getFooAsString()`, NOT `utils.foo.toString()` - When in doubt, use naming conventions from ActionScript and the FlashPlayer API. ###Packages Here are general guidelines for how to pick a package. * Check to see what packages already exist before creating a new one. If possible, use one of the existing packages. **Do not** use your own package names (e.g. `com.mimswright`) * If a utility function operates mainly on a particular class from the Flash Player API, use the same package name as that class. E.g. if your function deals mostly with `Sprites`, use the `utils.display` package. * If your function is related to a root-level class in the Flash API, such as `Array`, use `utils.array`. * If you have a significant set of functions that relates to a specific class within a package, you may create a new package just for that class. For example, if you have several functions that all deal with `Point`, could go in `utils.geom.point`. * If you're Peter Piper, pick a peck of pickled packages. ##Deprecating and Replacing Existing Code What do you do if you want to contribute a piece of code that is very similar to one that already exists? * **First, always check for code that could function similarly to your code.** * If you find similar code to something you want to commit, think carefully. * If your code and their code do virtually the same thing the same way, suck it up and **keep the existing code**. * Only edit or replace existing code if there are tests. If there are not tests, write tests against the existing code then replace with your version. Ensure the tests still pass before committing. * Writing a note explaining why you made the change is encouraged. * If you find checked-in code that is a duplicate of another piece of code, keep the one that is clearer and more robust and remove the other. * You may make changes to names of functions if they are unclear or don't meet the naming requirements but in general, try not to change things around based only on your personal style. ##Unit Tests Needless to say, code should not cause any compile errors or warnings. New code snippets must be covered by tests. Tests should demonstrate correct usage, with as many unique scenarios as the code is expected to handle. Fringe cases that may throw errors should be demonstrated if possible, e.g. passing `null` to a function that expects a parameter of type `Array`. Tests should be written using FlexUnit 4.0+. If you come across code that needs a unit test written for it, you are encouraged to write one. You will earn much karma. More on FlexUnit and Testing on [Elad Elrom's Blog](http://elromdesign.com/blog/2010/03/10/test-driven-development-tdd-with-flexunit-4-complete-tutorial/). ##Documentation Please add [ASDoc](http://help.adobe.com/en_US/flex/using/WSd0ded3821e0d52fe1e63e3d11c2f44bb7b-7fe7.html)-style documentation to everything. Your code should have at least these tags in every function or class. * `@author Your Name` * `@param paramName Description.` if there are any params * `@return Type Description.` if not `void` * `@throws package.ErrorType Description.` if it throws an error * `@example <listing version="3.0">code</listing>` for example code. (A good habit is write the example first, then the docs, then the tests, then the code.) * `@playerversion Flash 10.1` If your code will only work on a player later than 9.0 Example code is optional for simple functions but please include a description of what the code is designed to achieve and/or why you might want to use it. Include any licensing that applies to your functions. Feel free to add docs to other people's code if there are none. ##Merge Strategy Submitters should follow these steps when contributing code to the project. __SUBMITTERS:__ 1. Create a fork of the project. 1. Make your changes, test, and commit them. 1. When you're ready to integrate the changes into the main branch, create a pull request. 1. Don't merge your own pull request even if you're an admin. Instead, ask for assistance from someone else to review your pull request and merge it into the master. 1. If you're an admin and are anxious with waiting for your pull request to be handled, review and pull someone else's code while you wait. __ADMINS:__ 1. Review the commits by checking them out to a local repository. 1. Ask questions of the submitter or other admins! 1. Write tests & improve docs or request that the submitter do so. 1. Remember to run the test suite before merging code into master. +1. You can reformat the incoming code using the `res/flex-formatter.properties` file. (Optional) + 1. Big changes can/should first be merged into a separate integration branch at your discretion. ###Why not merge your own code? This is a collection made for everyone made up of several people's personal code library. The chances of adding duplicate or idiosyncratic code is very high. Using the pull-request scheme is a great way for us to make sure all the code is being reviewed by *someone* other than the author. The more people who review code the less chance of checking in a duplicate or buggy piece of code. Furthermore, gitHub is set up to handle a distributed repository workflow very elegantly. If at any point you want to break out and work on your own personal code library, that's easy to do in your own fork. \ No newline at end of file
as3/as3-utils
595457df6127918952ec09fe3ae47bfdc5ee97a6
Cleaned up a nasty corrupted branch
diff --git a/NOTES.md b/NOTES.md index 55f9102..30ef31a 100644 --- a/NOTES.md +++ b/NOTES.md @@ -1,251 +1,251 @@ # as3-utils # ISSUES - parameter names are not descriptive - variable names are not descriptive - nomenclature is inconsistent -- use functional-programming names? -- use designer friendly names? -- provide aliases for common functions with multiple common names? - ASDocs -- missing tags -- incorrect descriptions -- incorrect tags # Refactoring Guidelines - predicate methods should be prefixed with is* # AUDIT The below is the results of a quick audit of the functions available in as3-utils, and their specific issues. # ALIGN alignLeft alignToRectangleLeft duplicates alignRight alignToRectangleRight duplicates align to edges distribute by edges grid alignment hAlign(targets:Array, hSpacing:int = 0, alignment:Alignment = Alignment.LEFT):Array vAlign(targets:Array, vSpacing:int = 0, alignment:Alignment = Alignment.TOP):Array gAlign(targets:Array, columns:int, rows:int, hSpacing:int = 0, vSpacing:int = 0, alignment:Alignment = Alignment.TOP_LEFT):Array gAlign = gridAlign /** * Aligns all the target DisplayObjects by their left edge to the left-most target. * * Similar to the Flash IDE Alignment panel. */ alignLeft(targets:Vector.<DisplayObject>):Vector.<DisplayObject> /** * Aligns all the target DisplayObjects by their right edge to the right-most target. * * Similar to the Flash IDE Alignment panel. */ alignRight(targets:Vector.<DisplayObject>):Vector.<DisplayObject> /** * Aligns all the target DisplayObjects by their top edges to the top-most target. * * Similar to the Flash IDE Alignment panel. */ alignTop(targets:Vector.<DisplayObject>):Vector.<DisplayObject> /** * Aligns all the target DisplayObjects by their bottom edges to the bottom-most target. * * Similar to the Flash IDE Alignment panel. */ alignBottom(targets:Vector.<DisplayObject>):Vector.<DisplayObject> /** * Aligns all the target DisplayObjects by their horizontal center edges to the horizontal center of the all the targets. * * Similar to the Flash IDE Alignment panel. */ alignHorizontalCenter(targets:Vector.<DisplayObject>):Vector.<DisplayObject> /** * Aligns all the target DisplayObjects by their vertical center edges to the vertical center of the all the targets. * * Similar to the Flash IDE Alignment panel. */ alignVerticalCenter(targets:Vector.<DisplayObject>):Vector.<DisplayObject> alignToLeftEdge(of:DisplayObject, ...targets) alignLeftEdges(...targets):Array alignRightEdges(...targets):Array alignTopEdges(...targets):Array alignBottomEdges(...targets):Array alignCenters(...targets):Array distributeByLeftEdge(...targets):Array distributeByRightEdge(...targets):Array distributeByTopEdge(...targets):Array distributeByBottomEdge(...targets):Array distributeByHorizontalCenter(...targets):Array distributeByVerticalCenter(...targets):Array # ARRAY utils.array.contains():int badly named, should be something like numReferencesInArray, arrayRefCount utils.array.copyArray() remove, pointless, use array.slice() instead. utils.array.createUniqueCopy utils.array.removeDuplicates duplicates asx.array.unique utils.array.arraysAreEqual utils.array.equals duplicates utils.array.getHighestValue utils.array.getLowestValue use the Array constants, not magic numbers utils.array.randomize too much code for what it does could be faster utils.array.removeItem utils.array.removeValueFromArray duplicates utils.array.retainItems duplicates asx.array.union utils.array.sum duplicates asx.array.sum # ASSERT utils.assert.* suggestion: use the assertions provided by hamcrest-as3 or flexunit should throw an AssertionError instead of Error utils.capabilities.getPlayerInfo dubious value # CAPABILITIES utils.capabilities.isMac utils.capabilities.isPC change isMac to be !isPC DRY # COLOR utils.color.randomColor implementation is whack, why convert to a Number to a String to a Number? utils.color.toGrayscale which reference was used for the mix ratios? # COOKIE utils.cookie.setCookie potential global javascript namespace pollution # DATE utils.date.toRFC822 missing result examples, and appears to reference the wrong RFC number utils.date.toW3CDTF missing result examples # DISPLAY utils.display.addTargetToParent dubious value uses a switch for two values uses magic numbers utils.display.Alignment values should be same as key move to utils.align.Alignment eg BOTTOM_LEFT:String = "BOTTOM_LEFT" utils.display.sumProps remove replace with utils.number.sum, asx.object.pluck # ERROR utils.error.getStackTrace no try-catch required return new Error().getStackTrace(); dubious value # EVENT utils.event.addTargetEventListener utils.event.removeTargetEventListener dubious value # FRAME utils.frame.addFrameScript utils.frame.removeFrameScript needs an appropriate error message can multiple framescripts exist on a single frame? # GEOM utils.geom.Point3D move static methods to instance method, both deal with Point3D as arguments, and there are already instance methods for add, subtract, offset # NUMBER utils.number.clamp utils.number.confine utils.number.constrain utils.range.resolve duplicates asx.number.bound replace with clamp utils.number.insertCommas there is easier way to do this, using reverse, split and join utils.number.isBetween duplicates asx.number.between # RANGE utils.range.resolve duplicates utils.number.clamp etc # STRING utils.string.addSlashes bad name, escapeChars is more accurate utils.string.slashUnsafeChars bad name, escapeRegExpChars is more accurate utils.string.constants bad name, separate to package level or rename utils.string.firstToUpper bad name, rename to capitalize utils.string.replace dubious value utils.string.stripSlashes bad name, unescapeChars - \ No newline at end of file +
as3/as3-utils
5dc573bde85cc3aac7351159a413096f5c2c54d5
Fixed a bug in number to string
diff --git a/src/utils/number/toHex.as b/src/utils/number/toHex.as index a4de7ad..03ee7d8 100644 --- a/src/utils/number/toHex.as +++ b/src/utils/number/toHex.as @@ -1,42 +1,43 @@ package utils.number { import flash.utils.Endian; /** * Outputs the hex value of a int, allowing the developer to specify * the endian in the process. Hex output is lowercase. * @param n The int value to output as hex * @param endianness Flag to output the int as big or little endian. * Can be Endian.BIG_INDIAN/Endian.LITTLE_ENDIAN or true/false * @return A string of length 8 corresponding to the * hex representation of n ( minus the leading "0x" ) * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @see flash.utils.Endian * * @author Unknown. flash.utils.Endian tweak added by Mims Wright */ - public function toHex(n:int, endianness:* = Endian.LITTLE_ENDIAN):String { + public function toHex(n:int, endianness:* = null):String { var bigEndian:Boolean; + if (endianness == null) { endianness = Endian.LITTLE_ENDIAN; } if (endianness is Boolean) { bigEndian = Boolean(endianness); } else { bigEndian = endianness == Endian.BIG_ENDIAN; } var s:String = ""; if(bigEndian) { for(var i:int = 0; i < 4; i++) { s += hexChars.charAt((n >> ((3 - i) * 8 + 4)) & 0xF) + hexChars.charAt((n >> ((3 - i) * 8)) & 0xF); } } else { for(var x:int = 0; x < 4; x++) { s += hexChars.charAt((n >> (x * 8 + 4)) & 0xF) + hexChars.charAt((n >> (x * 8)) & 0xF); } } return s; } } diff --git a/src/utils/string/numberToString.as b/src/utils/string/numberToString.as new file mode 100644 index 0000000..5855b8c --- /dev/null +++ b/src/utils/string/numberToString.as @@ -0,0 +1,157 @@ +package utils.string +{ + /** + * Converts a number to its text equivelant + * + * @params n The number to convert + * @returns String equivelant of the number + * @playerversion Flash 10.0 + * @author Mims H. Wright + */ + public function numberToString(n:uint):String { + var str:String; // str will hold the final outcome + var output:Vector.<String> = new Vector.<String>(); // output will temporarily hold the strings that make up str + var digits:Vector.<String> = new Vector.<String>(); // digit is an array of digits based on the number n + var negative:Boolean = false; // used for removing minus sign. + + // check for zero + if (n == 0) { return N._0; } // todo: tidy + // check for negatives + if (n < 0) { + negative = true; + n *= -1; + } + + digits = Vector.<String>(n.toString().split("")); + + // reverse the array so that each order of ten can be represented by + // an element of the periods array. + digits.reverse(); + var max:Number = digits.length; + + // for each digit in n + var magnitude:int = 0; + for (;magnitude < max; magnitude+=1) { + var pos:int = magnitude; + + var digitInt:int = int(digits[pos]); + var periodForThisMagnitude:Vector.<String> = N.periods[magnitude]; +// var textForThisDigit:String = periodForThisMagnitude[digitInt] + // push the text equivelant to the output +// output.push(textForThisDigit); + output.push(N.periods[magnitude][digits[pos]]); + + // anytime ten is written it's a special case. + // the second magnitude and every 3 magnitudes after are special + var s:Number = magnitude % 3; + + // if this is a special case and output for special (tens) place is ten + if ((s == 1) && (output[magnitude] == N.periods[1][1])) { + // delete the value for the ones place + output[magnitude] = ""; + // choose a new value for tens using a special case + var newTxt:String + switch (int(digits[magnitude-1])) { + case (0) : newTxt = N._10; break; + case (1) : newTxt = N._11; break; + case (2) : newTxt = N._12; break; + case (3) : newTxt = N._13; break; + case (4) : newTxt = N._14; break; + case (5) : newTxt = N._15; break; + case (6) : newTxt = N._16; break; + case (7) : newTxt = N._17; break; + case (8) : newTxt = N._18; break; + case (9) : newTxt = N._19; break; + } + // replace the word 'ten' with the new text. + var spc:Number = output[magnitude-1].indexOf(" "); + output[magnitude-1] = newTxt + output[magnitude-1].substr(spc + 1); + } + } + + if (negative == true) { + output.push("negative "); + n *= -1; + } + + // reverse the output so that it will look correct + output.reverse(); + // save the output to the string + str = output.join(""); + return str; + } +} + +internal class N { + public static const _0:String = "zero"; + public static const _1:String = "one "; + public static const _2:String = "two "; + public static const _3:String = "three "; + public static const _4:String = "four "; + public static const _5:String = "five "; + public static const _6:String = "six "; + public static const _7:String = "seven "; + public static const _8:String = "eight "; + public static const _9:String = "nine "; + public static const _10:String = "ten "; + public static const _11:String = "eleven "; + public static const _12:String = "twelve "; + public static const _13:String = "thirteen "; + public static const _14:String = "fourteen "; + public static const _15:String = "fifteen "; + public static const _16:String = "sixteen "; + public static const _17:String = "seventeen "; + public static const _18:String = "eighteen "; + public static const _19:String = "nineteen "; + public static const _20:String = "twenty "; + public static const _30:String = "thirty "; + public static const _40:String = "fourty "; + public static const _50:String = "fifty "; + public static const _60:String = "sixty "; + public static const _70:String = "seventy "; + public static const _80:String = "eighty "; + public static const _90:String = "ninety "; + public static const _100:String = "hundred "; + public static const _1000:String = "thousand "; + public static const _1000000:String = "million "; + public static const _1000000000:String = "billion "; + public static const _1000000000000:String = "trillion "; + public static const _1000000000000000:String = "quadrillion "; + + + public static const _1to9:Vector.<String> = Vector.<String>(["",_1,_2,_3,_4,_5,_6,_7,_8,_9]); + public static const _10to90:Vector.<String> = Vector.<String>(["",_10,_20,_30,_40,_50,_60,_70,_80,_90]); + public static const _100to900:Vector.<String> = Vector.<String>(["",_1 + _100, _2 + _100, _3 + _100, _4 + _100, _5 + _100, _6 + _100, _7 + _100, _8 + _100, _9 + _100]); + + /** + * Period generator. Creates arrays of periods of numeric text equivelants. ie. 1thousand, 10thousand, 100thousand + * + * @param counter - the name of the period (ie 'billion') + * @returns array - an array of three arrays that represent the period, to be appended to the master period + */ + private static function createPeriod (counter:String):Vector.<Vector.<String>> { + var period:Vector.<Vector.<String>> = Vector.<Vector.<String>> ([ + Vector.<String>(["",_1 + counter, _2 + counter, _3 + counter, _4 + counter, _5 + counter, _6 + counter, _7 + counter, _8 + counter, _9 + counter]), + _10to90, + _100to900 + ]); + return period; + } + + // the text equivelants of all the numbers as a multi-dimensional array + public static function get periods():Vector.<Vector.<String>> { + if (_periods == null) { + _periods = new Vector.<Vector.<String>>(); + _periods = _periods.concat( + createPeriod(_1000000000000000), // quadril + createPeriod(_1000000000000), // tril + createPeriod(_1000000000), // bil + createPeriod(_1000000), // mil + createPeriod(_1000), + createPeriod("") + ); + } + return _periods; + } + private static var _periods:Vector.<Vector.<String>>; +} \ No newline at end of file
as3/as3-utils
2f1a5e2766ee14b3b2169c3faec8f0d30a99b308
tweaked checkDomain
diff --git a/src/utils/load/checkDomain.as b/src/utils/load/checkDomain.as index 1df98ad..ce6cd1c 100644 --- a/src/utils/load/checkDomain.as +++ b/src/utils/load/checkDomain.as @@ -1,38 +1,51 @@ package utils.load { - import flash.display.LoaderInfo - + import flash.display.LoaderInfo; + import flash.errors.IOError; + import flash.external.ExternalInterface; + /** * Ensures that the domain that loaded the app is from an approved list of domains. + * + * @example <listing version="3.0"> + * var approvedDomains:Array = [".*\.example\.com", ".*\.foo\.com", ".*\.me\.mysite\.com"]; + * try { + * var testPassed:Boolean = checkDomain(this.loaderInfo, approvedDomains); + * } catch (e:IOError) { + * // Domain check didn't pass. Stop the application. + * } + * // If there wasn't an error, continue the application. + * </listing> * + * @throws IOError If the domain isn't allowed. + * * @param loaderInfo The LoaderInfo object for the main app. * This would probably be your application's main class' loaderInfo. * @param allowedDomains An array of approved domains as RegExp strings. e.g. ".*\.example.com" - * - * @return Boolean True if the domain check passed and false if it failed. + * @return Boolean True if domain check passed. * * @author Mims H. Wright */ - // todo: Should this throw an error if it fails? public function checkDomain(loaderInfo:LoaderInfo, approvedDomains:Array):Boolean { var url:String; if (ExternalInterface.available) { url = ExternalInterface.call("window.location.href.toString"); } else { url = loaderInfo.loaderURL; } var allowedDomainsString:String = approvedDomains.join("|"); var allowedPattern:String = "(^"+allowedDomainsString+"/?)"; var domainCheck:RegExp = new RegExp(allowedPattern,"i"); var domainCheckResult:Object = domainCheck.exec(url); if (domainCheckResult == null) { // domain check failed, abort application + throw new IOError("You are not permitted to load this file from this location " + url); return false; } else { // domain okay, proceed return true; } } } \ No newline at end of file
as3/as3-utils
600beb0f0bc7d473d73d89e070af90b16c4fdadb
Added domain check that checks the domain that loaded the swf file against a list of approved domains.
diff --git a/src/utils/load/checkDomain.as b/src/utils/load/checkDomain.as new file mode 100644 index 0000000..1df98ad --- /dev/null +++ b/src/utils/load/checkDomain.as @@ -0,0 +1,38 @@ +package utils.load +{ + import flash.display.LoaderInfo + + /** + * Ensures that the domain that loaded the app is from an approved list of domains. + * + * @param loaderInfo The LoaderInfo object for the main app. + * This would probably be your application's main class' loaderInfo. + * @param allowedDomains An array of approved domains as RegExp strings. e.g. ".*\.example.com" + * + * @return Boolean True if the domain check passed and false if it failed. + * + * @author Mims H. Wright + */ + // todo: Should this throw an error if it fails? + public function checkDomain(loaderInfo:LoaderInfo, approvedDomains:Array):Boolean { + var url:String; + if (ExternalInterface.available) { + url = ExternalInterface.call("window.location.href.toString"); + } else { + url = loaderInfo.loaderURL; + } + + var allowedDomainsString:String = approvedDomains.join("|"); + var allowedPattern:String = "(^"+allowedDomainsString+"/?)"; + + var domainCheck:RegExp = new RegExp(allowedPattern,"i"); + var domainCheckResult:Object = domainCheck.exec(url); + if (domainCheckResult == null) { + // domain check failed, abort application + return false; + } else { + // domain okay, proceed + return true; + } + } +} \ No newline at end of file
as3/as3-utils
9e07646b00f36874809e62e2c12107b9ebde030d
Removed addTargetEventListener.as and removeTargetEventListener.as since they barely do anything. Added Direction.as
diff --git a/src/utils/event/addTargetEventListener.as b/src/utils/event/addTargetEventListener.as deleted file mode 100644 index 9258b62..0000000 --- a/src/utils/event/addTargetEventListener.as +++ /dev/null @@ -1,12 +0,0 @@ -package utils.event -{ - import flash.display.DisplayObject; - - public function addTargetEventListener(_target:DisplayObject, _type:String, _listener:Function, _useCapture:Boolean = false, _priority:int = 0, _useWeakReference:Boolean = true):void - { - if (_target != null) - { - _target.addEventListener(_type, _listener, _useCapture, _priority, _useWeakReference); - } - } -} \ No newline at end of file diff --git a/src/utils/event/removeTargetEventListener.as b/src/utils/event/removeTargetEventListener.as deleted file mode 100644 index 0dc0662..0000000 --- a/src/utils/event/removeTargetEventListener.as +++ /dev/null @@ -1,12 +0,0 @@ -package utils.event -{ - import flash.display.DisplayObject; - - public function removeTargetEventListener(_target:DisplayObject, _type:String, _listener:Function, _useCapture:Boolean = false):void - { - if (_target != null) - { - _target.removeEventListener(_type, _listener, _useCapture); - } - } -} \ No newline at end of file diff --git a/src/utils/geom/Direction.as b/src/utils/geom/Direction.as new file mode 100644 index 0000000..c18ee41 --- /dev/null +++ b/src/utils/geom/Direction.as @@ -0,0 +1,29 @@ +package utils.geom +{ + + /** + * An enumeration of the four cardinal directions. + * Mirrors the directions in Side. + * + * Make a hybrid direction using '|', e.g. <code>var NW:int = NORTH | WEST;</code> + * + * @author Mims Wright + * + * @see utils.geom.Side + */ + public class Direction + { + public static const UP:int = 1; + public static const DOWN:int = 2; + public static const LEFT:int = 4; + public static const RIGHT:int = 8; + + public static const NORTH:int = UP; + public static const SOUTH:int = DOWN; + public static const WEST:int = LEFT; + public static const EAST:int = RIGHT; + + public static const NONE:int = 0; + public static const ALL:int = UP | DOWN | LEFT | RIGHT; + } +} \ No newline at end of file
as3/as3-utils
872d84917a8102e20dad9d0e2b5c88492f709c31
changed addTargetEvenListener default params
diff --git a/src/utils/event/addTargetEventListener.as b/src/utils/event/addTargetEventListener.as index 3020136..1628c4e 100644 --- a/src/utils/event/addTargetEventListener.as +++ b/src/utils/event/addTargetEventListener.as @@ -1,16 +1,16 @@ package utils.event { import flash.events.IEventDispatcher; public function addTargetEventListener(target:IEventDispatcher, type:String, listener:Function, - useWeakReference:Boolean = true, + useWeakReference:Boolean = false, useCapture:Boolean = false, priority:int = 0):void { if(!target) return; target.addEventListener(type, listener, useCapture, priority, useWeakReference); } } \ No newline at end of file
as3/as3-utils
adbb1183dcec18924bee691d2e14f1b9ab560f2f
While we're in the business of rewriting the addEventListener function signature, why not promote the importance of the useWeakListener argument? Also, drops the dependency on DisplayObject in favor of IEventDispatcher.
diff --git a/src/utils/event/addTargetEventListener.as b/src/utils/event/addTargetEventListener.as index 9258b62..3020136 100644 --- a/src/utils/event/addTargetEventListener.as +++ b/src/utils/event/addTargetEventListener.as @@ -1,12 +1,16 @@ package utils.event { - import flash.display.DisplayObject; + import flash.events.IEventDispatcher; - public function addTargetEventListener(_target:DisplayObject, _type:String, _listener:Function, _useCapture:Boolean = false, _priority:int = 0, _useWeakReference:Boolean = true):void + public function addTargetEventListener(target:IEventDispatcher, + type:String, + listener:Function, + useWeakReference:Boolean = true, + useCapture:Boolean = false, + priority:int = 0):void { - if (_target != null) - { - _target.addEventListener(_type, _listener, _useCapture, _priority, _useWeakReference); - } + if(!target) return; + + target.addEventListener(type, listener, useCapture, priority, useWeakReference); } } \ No newline at end of file diff --git a/src/utils/event/removeTargetEventListener.as b/src/utils/event/removeTargetEventListener.as index 0dc0662..51c0adf 100644 --- a/src/utils/event/removeTargetEventListener.as +++ b/src/utils/event/removeTargetEventListener.as @@ -1,12 +1,15 @@ package utils.event { import flash.display.DisplayObject; + import flash.events.IEventDispatcher; - public function removeTargetEventListener(_target:DisplayObject, _type:String, _listener:Function, _useCapture:Boolean = false):void + public function removeTargetEventListener(target:IEventDispatcher, + type:String, + listener:Function, + useCapture:Boolean = false):void { - if (_target != null) - { - _target.removeEventListener(_type, _listener, _useCapture); - } + if(!target) return; + + target.removeEventListener(type, listener, useCapture); } } \ No newline at end of file
as3/as3-utils
59d2de6052a61d597b5e9a985553672118d80f48
Typos & docs update
diff --git a/build.xml b/build.xml index f6581cc..1650c15 100644 --- a/build.xml +++ b/build.xml @@ -1,236 +1,237 @@ <?xml version="1.0"?> -<project - name="as3-utils" - basedir="." - default="package"> - +<project + name="as3-utils" + basedir="." + default="package"> + <!-- as3-utils usage: $ ant -v clean package @author drewbourne --> - + <!-- properties --> <property environment="env" /> <property file="build.properties" /> <!-- paths: existing --> <property name="src.loc" location="${basedir}/src" /> <property name="test.loc" location="${basedir}/test" /> <property name="lib.loc" location="${basedir}/libs" /> <property name="build.loc" location="${basedir}/build" /> <property name="build.pmd.loc" location="${build.loc}/pmd" /> <property name="build.flexunit.loc" location="${build.loc}/flexunit" /> - <!-- paths: enerated --> + <!-- paths: enumerated --> <property name="dist.loc" location="${basedir}/target" /> <property name="bin.loc" location="${dist.loc}/bin" /> <property name="doc.loc" location="${dist.loc}/doc" /> <property name="report.loc" location="${dist.loc}/report" /> <property name="report.flexunit.loc" location="${report.loc}/flexunit" /> <!-- Flex SDK --> <property name="FLEX_HOME" location="${env.FLEX_HOME}" /> - <!-- taskdefs --> - <taskdef resource="flexTasks.tasks" - classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> - + <!-- task definitions --> + <taskdef resource="flexTasks.tasks" + classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> + <!-- targets --> <target - name="clean" - description="Removes generated artifacts and directories"> - + name="clean" + description="Removes generated artifacts and directories"> + <delete dir="${dist.loc}" /> - + </target> - - <target - name="initialize" - description="Creates generated directories "> - + + <target + name="initialize" + description="Creates generated directories "> + <mkdir dir="${dist.loc}" /> <mkdir dir="${bin.loc}" /> <mkdir dir="${doc.loc}" /> <mkdir dir="${report.loc}" /> <mkdir dir="${report.flexunit.loc}" /> - + </target> - - <target - name="compile-check-if-required" - description="Checks if a compile is required" - depends="initialize"> - - <uptodate - property="compile.not-required" - targetfile="${bin.loc}/${build.artifact}.swc"> + + <target + name="compile-check-if-required" + description="Checks if a compile is required" + depends="initialize"> + + <uptodate + property="compile.not-required" + targetfile="${bin.loc}/${build.artifact}.swc"> <srcresources> <fileset dir="${src.loc}"> <include name="**/*.as" /> <include name="**/*.mxml" /> </fileset> <fileset dir="${lib.loc}"> <include name="**/*.swc" /> </fileset> </srcresources> </uptodate> - + </target> - - <target - name="compile" - description="Compiles the library" - depends="initialize, compile-check-if-required" - unless="compile.not-required"> - + + <target + name="compile" + description="Compiles the library" + depends="initialize, compile-check-if-required" + unless="compile.not-required"> + <compc output="${bin.loc}/${build.artifact}.swc"> <source-path path-element="${src.loc}" /> - + <include-sources dir="${src.loc}"> <include name="**/*.as" /> <include name="**/*.mxml" /> </include-sources> - + <library-path dir="${lib.loc}" append="true"> <include name="*.swc" /> </library-path> - + <compiler.verbose-stacktraces>true</compiler.verbose-stacktraces> <compiler.headless-server>true</compiler.headless-server> </compc> - + </target> - <target name="test" - description="Run the test suite" - depends="initialize"> - - <taskdef resource="flexUnitTasks.tasks" - classpath="${build.flexunit.loc}/flexUnitTasks-${flexunit.version}.jar" /> - + <target name="test" + description="Run the test suite" + depends="initialize"> + + <taskdef resource="flexUnitTasks.tasks" + classpath="${build.flexunit.loc}/flexUnitTasks-${flexunit.version}.jar" /> + <!-- Compile Test --> - <mxmlc - file="${test.loc}/${test.runner}.${test.runner.ext}" - output="${bin.loc}/${test.runner}.swf"> - + <mxmlc + file="${test.loc}/${test.runner}.${test.runner.ext}" + output="${bin.loc}/${test.runner}.swf"> + <library-path dir="${bin.loc}" append="true"> <include name="${build.artifact}.swc" /> </library-path> <library-path dir="${lib.loc}" append="true"> <include name="*.swc" /> </library-path> <compiler.verbose-stacktraces>true</compiler.verbose-stacktraces> <compiler.headless-server>true</compiler.headless-server> </mxmlc> <!-- Execute Tests --> - <flexunit - swf="${bin.loc}/${test.runner}.swf" - toDir="${report.flexunit.loc}" - headless="true" - haltonfailure="false" - verbose="true" - localTrusted="true" /> - + <flexunit + swf="${bin.loc}/${test.runner}.swf" + toDir="${report.flexunit.loc}" + headless="true" + haltonfailure="false" + verbose="true" + localTrusted="true" /> + </target> - <target name="report" - description="Generates test reports from FlexUnit, FlexPMD, FlexCPD, FlexMetrics" - depends="test"> - + <target name="report" + description="Generates test reports from FlexUnit, FlexPMD, FlexCPD, FlexMetrics" + depends="test"> + <!-- Generate readable report for FlexUnit --> <junitreport todir="${report.flexunit.loc}"> <fileset dir="${report.flexunit.loc}"> <include name="TEST-*.xml" /> </fileset> <report format="frames" todir="${report.flexunit.loc}/html" /> </junitreport> <!-- FlexPMD config --> <path id="flexpmd.base"> <pathelement location="${build.pmd.loc}/as3-parser-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/as3-parser-api-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/as3-plugin-utils-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/flex-pmd-files-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/pmd-4.2.5.jar" /> </path> <taskdef name="pmd" classname="com.adobe.ac.pmd.ant.FlexPmdAntTask" classpath="${build.pmd.loc}/flex-pmd-ant-task-${flexpmd.version}.jar"> <classpath> <path refid="flexpmd.base" /> <pathelement location="${build.pmd.loc}/commons-lang-2.4.jar" /> <pathelement location="${build.pmd.loc}/flex-pmd-core-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/flex-pmd-ruleset-api-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/flex-pmd-ruleset-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/plexus-utils-1.0.2.jar" /> </classpath> </taskdef> <taskdef name="cpd" classname="com.adobe.ac.cpd.ant.FlexCpdAntTask" classpath="${build.pmd.loc}/flex-pmd-cpd-ant-task-${flexpmd.version}.jar"> <classpath> <path refid="flexpmd.base" /> <pathelement location="${build.pmd.loc}/flex-pmd-cpd-${flexpmd.version}.jar" /> </classpath> </taskdef> - <taskdef name="metrics" classname="com.adobe.ac.pmd.metrics.ant.FlexMetricsAntTask" classpath="${build.pmd.loc}/flex-pmd-metrics-ant-task-${flexpmd.version}.jar"> + <taskdef name="metrics" classname="com.adobe.ac.pmd.metrics.ant.FlexMetricsAntTask" + classpath="${build.pmd.loc}/flex-pmd-metrics-ant-task-${flexpmd.version}.jar"> <classpath> <path refid="flexpmd.base" /> <pathelement location="${build.pmd.loc}/commons-lang-2.4.jar" /> <pathelement location="${build.pmd.loc}/dom4j-1.6.1.jar" /> <pathelement location="${build.pmd.loc}/flex-pmd-metrics-${flexpmd.version}.jar" /> <pathelement location="${build.pmd.loc}/flex-pmd-ruleset-api-${flexpmd.version}.jar" /> </classpath> </taskdef> <!-- Executions --> <pmd sourceDirectory="${src.loc}" outputDirectory="${report.loc}" /> <cpd minimumTokenCount="50" outputFile="${report.loc}/cpd.xml"> <fileset dir="${src.loc}"> <include name="**/*.as" /> <include name="**/*.mxml" /> </fileset> </cpd> <metrics sourcedirectory="${src.loc}" outputfile="${report.loc}/javancss.xml" /> - + </target> - + <target name="doc" - description="Generate ASDoc for ${ant.project.name}" - depends="initialize"> - + description="Generate ASDoc for ${ant.project.name}" + depends="initialize"> + <!-- Generate asdocs --> <java jar="${FLEX_HOME}/lib/asdoc.jar" fork="true" failonerror="true"> <arg line="+flexlib '${FLEX_HOME}/frameworks'" /> <arg line="-doc-sources '${src.loc}'" /> <arg line="-source-path+='${src.loc}'" /> <arg line="-output '${doc.loc}'" /> <arg line="-main-title '${project.name} API Documentation'" /> <arg line="-window-title '${project.name} API Documentation'" /> </java> - + </target> - <target name="package" - description="Package ${ant.project.name} into a zip" - depends="compile, test, report, doc"> + <target name="package" + description="Package ${ant.project.name} into a zip" + depends="compile, test, report, doc"> <!-- Create distribution for binaries with docs --> <zip destfile="${dist.loc}/${build.artifact}.zip"> <zipfileset dir="${bin.loc}"> <include name="${build.artifact}.swc" /> </zipfileset> <zipfileset dir="${doc.loc}" prefix="doc" /> </zip> - + </target> - -</project> \ No newline at end of file + +</project> diff --git a/src/utils/align/alignCenter.as b/src/utils/align/alignCenter.as index 04288db..37cd7fa 100644 --- a/src/utils/align/alignCenter.as +++ b/src/utils/align/alignCenter.as @@ -1,13 +1,13 @@ -package utils.align -{ +package utils.align { import flash.display.DisplayObject; + + /** * Center align object to target. */ - public function alignCenter(item:DisplayObject, target:DisplayObject):void - { + public function alignCenter(item:DisplayObject, target:DisplayObject):void { xAlignCenter(item, target); yAlignCenter(item, target); } -} \ No newline at end of file +} diff --git a/src/utils/align/horizontalAlign.as b/src/utils/align/horizontalAlign.as index 0a76737..eb89433 100644 --- a/src/utils/align/horizontalAlign.as +++ b/src/utils/align/horizontalAlign.as @@ -1,23 +1,21 @@ -package utils.align -{ +package utils.align { + + + /** - * Convienent horizontal align method with optional alignment argument - * + * Convenient horizontal align method with optional alignment argument * @example <listing version="3.0">Alignment.hAlign( [ clip0, clip1, clip2], 10 );</listing> - * * @param items An array of items - * @param optional spacing The spacing between items in pixels as either a number or array or blank + * @param args spacing The spacing between items in pixels as either a number or array or blank */ - public function horizontalAlign(items:Array, ... args):void - { - if (args.length > 0) - { - if (args[0] is Array) + public function horizontalAlign(items:Array, ... args):void { + if(args.length > 0) { + if(args[0] is Array) horizontalAlignSpaceArray(items, args[0]); - if (args[0] is Number) + if(args[0] is Number) horizontalAlignSpaceNumber(items, args[0]); } else horizontalAlignNoSpace(items); } -} \ No newline at end of file +} diff --git a/src/utils/align/horizontalAlignSpaceArray.as b/src/utils/align/horizontalAlignSpaceArray.as index 30b3c4b..dbdaa67 100644 --- a/src/utils/align/horizontalAlignSpaceArray.as +++ b/src/utils/align/horizontalAlignSpaceArray.as @@ -1,21 +1,19 @@ -package utils.align -{ +package utils.align { + + + /** - * Aligns each item in the array to the one preceeding it. + * Aligns each item in the array to the one preceding it. * Uses the correlating position in the spacing arr for the spacing. - * * @example <listing version="3.0">Alignment.hAlignSpaceArr( [ clip0, clip1, clip2], [ 0, 5, 30 ] );</listing> - * * @param items An array of items * @param spacing The array for spacing between items in pixels */ - public function horizontalAlignSpaceArray(items:Array, spacing:Array):void - { + public function horizontalAlignSpaceArray(items:Array, spacing:Array):void { var n:int = items.length; - for (var i:int = 1; i < n; i++) - { + for(var i:int = 1; i < n; i++) { items[i].x = items[(i - 1)].x + items[(i - 1)].width + spacing[i]; } } -} \ No newline at end of file +} diff --git a/src/utils/align/verticalAlign.as b/src/utils/align/verticalAlign.as index a92b4c3..7777bc1 100644 --- a/src/utils/align/verticalAlign.as +++ b/src/utils/align/verticalAlign.as @@ -1,23 +1,21 @@ -package utils.align -{ +package utils.align { + + + /** - * Convienent vertical allign method with optional alignment argument - * + * Convenient vertical align method with optional alignment argument * @example <listing version="3.0">Alignment.vAlign( [ clip0, clip1, clip2], 10 );</listing> - * * @param items An array of items - * @param optional spacing The spacing between items in pixels as either a number or array or blank + * @param spacingValues spacing The spacing between items in pixels as either a number or array or blank */ - public function verticalAlign(items:Array, ... spacingValues):void - { - if (spacingValues.length > 0) - { - if (spacingValues[0] is Array) + public function verticalAlign(items:Array, ... spacingValues):void { + if(spacingValues.length > 0) { + if(spacingValues[0] is Array) verticalAlignSpaceArray(items, spacingValues[0]); - if (spacingValues[0] is Number) + if(spacingValues[0] is Number) verticalAlignSpaceNumber(items, spacingValues[0]); } else verticalAlignNoSpace(items); } -} \ No newline at end of file +} diff --git a/src/utils/align/verticalAlignSpaceArray.as b/src/utils/align/verticalAlignSpaceArray.as index a8d2fd5..784d275 100644 --- a/src/utils/align/verticalAlignSpaceArray.as +++ b/src/utils/align/verticalAlignSpaceArray.as @@ -1,20 +1,18 @@ -package utils.align -{ +package utils.align { + + + /** - * Aligns each item in the array to the one preceeding it. + * Aligns each item in the array to the one preceding it. * Uses the correlating position in the spacing arr for the spacing. - * * @example <listing version="3.0">Alignment.valignSpaceArr( [ clip0, clip1, clip2], [ 0, 5, 30 ] );</listing> - * * @param items An array of items * @param spacing The array for spacing between items in pixels */ - public function verticalAlignSpaceArray(items:Array, spacing:Array):void - { + public function verticalAlignSpaceArray(items:Array, spacing:Array):void { var n:int = items.length; - for (var i:int = 1; i < n; i++) - { + for(var i:int = 1; i < n; i++) { items[i].y = int(items[(i - 1)].y + items[(i - 1)].height + spacing[i]); } } -} \ No newline at end of file +} diff --git a/src/utils/color/RGBtoHSL.as b/src/utils/color/RGBtoHSL.as index 1e17a25..786dc0e 100644 --- a/src/utils/color/RGBtoHSL.as +++ b/src/utils/color/RGBtoHSL.as @@ -1,45 +1,43 @@ -package utils.color -{ +package utils.color { + + + /** - * Convert an RGB Hexidecimal value to HSL values + * Convert an RGB Hexadecimal value to HSL values * @param red 0 - 1 scale. * @param green 0 - 1 scale. * @param blue 0 - 1 scale. * @return Object with h (hue), l (lightness), s (saturation) values:<ul> * <li><code>h</code> on 0 - 360 scale.</li> * <li><code>l</code> on 0 - 255 scale.</li> * <li><code>s</code> on 0 - 1 scale.</li></ul> */ - public function RGBtoHSL(red:Number, green:Number, blue:Number):Object - { + public function RGBtoHSL(red:Number, green:Number, blue:Number):Object { var min:Number, max:Number, delta:Number, l:Number, s:Number, h:Number = 0; max = Math.max(red, Math.max(green, blue)); min = Math.min(red, Math.min(green, blue)); //l = (min + max) / 2; l = (min + max) * 0.5; // L - if (l == 0) - { + if(l == 0) { return { h: h, l: 0, s: 1 }; } //delta = (max - min) / 2; delta = (max - min) * 0.5; - if (l < 0.5) - { + if(l < 0.5) { // S s = delta / l; } - else - { + else { s = delta / (1 - l); } // H h = RGBToHue(red, green, blue); return { h: h, l: l, s: s }; } -} \ No newline at end of file +} diff --git a/src/utils/color/changeContrast.as b/src/utils/color/changeContrast.as index ef49c8b..36f3d5c 100644 --- a/src/utils/color/changeContrast.as +++ b/src/utils/color/changeContrast.as @@ -1,19 +1,19 @@ -package utils.color -{ +package utils.color { import utils.number.clamp; + + /** - * Change the contrast of a hexidecimal Number by a certain increment + * Change the contrast of a hexadecimal Number by a certain increment * @param hex color value to shift contrast on * @param inc increment value to shift * @return new hex color value */ - public function changeContrast(hex:Number, inc:Number):Number - { + public function changeContrast(hex:Number, inc:Number):Number { var o:Object = getRGB(hex); o.r = clamp(o.r + inc, 0, 255); o.g = clamp(o.g + inc, 0, 255); o.b = clamp(o.b + inc, 0, 255); return toRGBComponents(o.r, o.g, o.b); } -} \ No newline at end of file +} diff --git a/src/utils/color/getHexStringFromARGB.as b/src/utils/color/getHexStringFromARGB.as index 5ff6af8..f899dab 100644 --- a/src/utils/color/getHexStringFromARGB.as +++ b/src/utils/color/getHexStringFromARGB.as @@ -1,29 +1,29 @@ -package utils.color -{ - /** - Converts a 32-bit ARGB color value into a hexidecimal String representation. +package utils.color { + - @param a: A uint from 0 to 255 representing the alpha value. - @param r: A uint from 0 to 255 representing the red color value. - @param g: A uint from 0 to 255 representing the green color value. - @param b: A uint from 0 to 255 representing the blue color value. - @return Returns a hexidecimal color as a String. - @example - <code> - var hexColor : String = ColorUtil.getHexStringFromARGB(128, 255, 0, 255); - trace(hexColor); // Traces 80FF00FF - </code> + + /** + Converts a 32-bit ARGB color value into a hexadecimal String representation. + @param a A uint from 0 to 255 representing the alpha value. + @param r A uint from 0 to 255 representing the red color value. + @param g A uint from 0 to 255 representing the green color value. + @param b A uint from 0 to 255 representing the blue color value. + @return Returns a hexadecimal color as a String. + @example + <code> + var hexColor : String = ColorUtil.getHexStringFromARGB(128, 255, 0, 255); + trace(hexColor); // Traces 80FF00FF + </code> */ - public function getHexStringFromARGB(a:uint, r:uint, g:uint, b:uint):String - { + public function getHexStringFromARGB(a:uint, r:uint, g:uint, b:uint):String { var aa:String = a.toString(16); var rr:String = r.toString(16); var gg:String = g.toString(16); var bb:String = b.toString(16); aa = (aa.length == 1) ? '0' + aa : aa; rr = (rr.length == 1) ? '0' + rr : rr; gg = (gg.length == 1) ? '0' + gg : gg; bb = (bb.length == 1) ? '0' + bb : bb; return (aa + rr + gg + bb).toUpperCase(); } -} \ No newline at end of file +} diff --git a/src/utils/color/getHexStringFromRGB.as b/src/utils/color/getHexStringFromRGB.as index fbbf941..968a399 100644 --- a/src/utils/color/getHexStringFromRGB.as +++ b/src/utils/color/getHexStringFromRGB.as @@ -1,26 +1,26 @@ -package utils.color -{ - /** - Converts an RGB color value into a hexidecimal String representation. +package utils.color { + - @param r: A uint from 0 to 255 representing the red color value. - @param g: A uint from 0 to 255 representing the green color value. - @param b: A uint from 0 to 255 representing the blue color value. - @return Returns a hexidecimal color as a String. - @example - <code> - var hexColor : String = ColorUtil.getHexStringFromRGB(255, 0, 255); - trace(hexColor); // Traces FF00FF - </code> + + /** + Converts an RGB color value into a hexadecimal String representation. + @param r A uint from 0 to 255 representing the red color value. + @param g A uint from 0 to 255 representing the green color value. + @param b A uint from 0 to 255 representing the blue color value. + @return Returns a hexadecimal color as a String. + @example + <code> + var hexColor : String = ColorUtil.getHexStringFromRGB(255, 0, 255); + trace(hexColor); // Traces FF00FF + </code> */ - public function getHexStringFromRGB(r:uint, g:uint, b:uint):String - { + public function getHexStringFromRGB(r:uint, g:uint, b:uint):String { var rr:String = r.toString(16); var gg:String = g.toString(16); var bb:String = b.toString(16); rr = (rr.length == 1) ? '0' + rr : rr; gg = (gg.length == 1) ? '0' + gg : gg; bb = (bb.length == 1) ? '0' + bb : bb; return (rr + gg + bb).toUpperCase(); } -} \ No newline at end of file +} diff --git a/src/utils/color/toHTML.as b/src/utils/color/toHTML.as index 842df2b..1e7a06e 100644 --- a/src/utils/color/toHTML.as +++ b/src/utils/color/toHTML.as @@ -1,10 +1,11 @@ -package utils.color -{ +package utils.color { + + + /** - * Convert a hexidecimal number to a string representation with HTML notation: <code>#rrggbb</code>. + * Convert a hexadecimal number to a string representation with HTML notation: <code>#rrggbb</code>. */ - public function toHTML(hex:uint):String - { + public function toHTML(hex:uint):String { return "#" + (hex.toString(16)).toUpperCase(); } -} \ No newline at end of file +} diff --git a/src/utils/color/toHexString.as b/src/utils/color/toHexString.as index 6fdd732..01a52da 100644 --- a/src/utils/color/toHexString.as +++ b/src/utils/color/toHexString.as @@ -1,10 +1,11 @@ -package utils.color -{ +package utils.color { + + + /** - * Convert a hexidecimal number to a string representation with ECMAScript notation: <code>0xrrggbb</code>. + * Convert a hexadecimal number to a string representation with ECMAScript notation: <code>0xrrggbb</code>. */ - public function toHexString(hex:uint):String - { + public function toHexString(hex:uint):String { return "0x" + (hex.toString(16)).toUpperCase(); } -} \ No newline at end of file +} diff --git a/src/utils/color/toRGBComponents.as b/src/utils/color/toRGBComponents.as index 08d0490..03c865a 100644 --- a/src/utils/color/toRGBComponents.as +++ b/src/utils/color/toRGBComponents.as @@ -1,14 +1,15 @@ -package utils.color -{ +package utils.color { + + + /** - * Convert individual R,G,B values to a hexidecimal value. + * Convert individual R,G,B values to a hexadecimal value. */ - public function toRGBComponents(r:uint, g:uint, b:uint):uint - { + public function toRGBComponents(r:uint, g:uint, b:uint):uint { var hex:uint = 0; hex += (r << 16); hex += (g << 8); hex += (b); return hex; } -} \ No newline at end of file +} diff --git a/src/utils/date/makeNight.as b/src/utils/date/makeNight.as index efd0266..ccb802d 100644 --- a/src/utils/date/makeNight.as +++ b/src/utils/date/makeNight.as @@ -1,15 +1,16 @@ -package utils.date -{ +package utils.date { + + + /** - * Converts a date into just befor midnight. + * Converts a date into just before midnight. */ - public function makeNight(d:Date):Date - { + public function makeNight(d:Date):Date { var d:Date = new Date(d.time); d.hours = 23; d.minutes = 59; d.seconds = 59; d.milliseconds = 999; return d; } -} \ No newline at end of file +} diff --git a/src/utils/geom/simplifyAngle.as b/src/utils/geom/simplifyAngle.as index 911af54..83043cc 100644 --- a/src/utils/geom/simplifyAngle.as +++ b/src/utils/geom/simplifyAngle.as @@ -1,21 +1,21 @@ package utils.geom { /** - * Simplifys the supplied angle to its simpliest representation. + * Simplifies the supplied angle to its simplest representation. * Example code: * <pre> * var simpAngle:Number = simplifyAngle(725); // returns 5 * var simpAngle2:Number = simplifyAngle(-725); // returns -5 * </pre> * @param value Angle to simplify * @return Supplied angle simplified * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function simplifyAngle(value:Number):Number { var _rotations:Number = Math.floor(value / 360); return (value >= 0) ? value - (360 * _rotations) : value + (360 * _rotations); } } diff --git a/src/utils/library/getBitmapDataFromLibrary.as b/src/utils/library/getBitmapDataFromLibrary.as index b23a5ee..59b5407 100644 --- a/src/utils/library/getBitmapDataFromLibrary.as +++ b/src/utils/library/getBitmapDataFromLibrary.as @@ -1,31 +1,28 @@ -package utils.library -{ +package utils.library { import flash.display.BitmapData; + + /** - * Get an instance of a BitmapData from the clip's library + * Get an instance of a BitmapData from the clip library * @param className Name of the BitmapData's class (aka. linkage ID) * @return An instance of the BitmapData with the given name or null if * the class cannot be found or the BitmapData cannot be * instantiated * @author Jackson Dunstan */ - public function getBitmapDataFromLibrary(className:String):BitmapData - { + public function getBitmapDataFromLibrary(className:String):BitmapData { var clazz:Class = getClassFromLibrary(className); - if (!clazz) - { + if(!clazz) { return null; } - try - { + try { // Need to pass a width and height, but they are ignored return new clazz(0, 0); } - catch (err:ArgumentError) - { + catch (err:ArgumentError) { return null; } return null; } -} \ No newline at end of file +} diff --git a/src/utils/library/getClassFromLibrary.as b/src/utils/library/getClassFromLibrary.as index f3ce9b0..cca29dc 100644 --- a/src/utils/library/getClassFromLibrary.as +++ b/src/utils/library/getClassFromLibrary.as @@ -1,26 +1,24 @@ -package utils.library -{ +package utils.library { + + + /** - * Get a class from the clip's library + * Get a class from the clip library * @param className Name of the class to get * @return The class with the given name or null if it cannot be found * @author Jackson Dunstan */ - public function getClassFromLibrary(className:String):Class - { - try - { + public function getClassFromLibrary(className:String):Class { + try { return Class(this.loaderInfo.applicationDomain.getDefinition(className)); } - catch (refErr:ReferenceError) - { + catch (refErr:ReferenceError) { return null; } - catch (typeErr:TypeError) - { + catch (typeErr:TypeError) { return null; } return null; } -} \ No newline at end of file +} diff --git a/src/utils/library/getClipFromLibrary.as b/src/utils/library/getClipFromLibrary.as index ab6fa85..1547577 100644 --- a/src/utils/library/getClipFromLibrary.as +++ b/src/utils/library/getClipFromLibrary.as @@ -1,29 +1,26 @@ -package utils.library -{ +package utils.library { import flash.display.MovieClip; + + /** - * Get an instance of a clip from the clip's library - * @param className Name of the clip's class (aka. linkage ID) + * Get an instance of a clip from the clip library + * @param className Name of the clip class (aka. linkage ID) * @return An instance of the clip with the given name or null if the * class cannot be found or the clip cannot be instantiated * @author Jackson Dunstan */ - public function getClipFromLibrary(className:String):MovieClip - { + public function getClipFromLibrary(className:String):MovieClip { var clazz:Class = getClassFromLibrary(className); - if (!clazz) - { + if(!clazz) { return null; } - try - { + try { return new clazz(); } - catch (err:ArgumentError) - { + catch (err:ArgumentError) { return null; } return null; } -} \ No newline at end of file +} diff --git a/src/utils/location/getDomain.as b/src/utils/location/getDomain.as index f9bb6e6..2e94847 100644 --- a/src/utils/location/getDomain.as +++ b/src/utils/location/getDomain.as @@ -1,24 +1,24 @@ package utils.location { import flash.display.DisplayObject; /** - * Detects MovieClip's domain location. + * Detects MovieClip domain location. * Function does not return folder path or file name. The method also treats "www" and sans "www" as the same; if "www" is present method does not return it. * Example code: * <pre> * trace(getDomain(_root)); * </pre> * @param location MovieClip to get location of - * @return Full domain (including sub-domains) of MovieClip's location + * @return Full domain (including sub-domains) of MovieClip location * @author Aaron Clinger * @author Shane McCartney * @author David Nelson * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function getDomain(location:DisplayObject):String { var baseUrl:String = location.loaderInfo.url.split("://")[1].split("/")[0]; return (baseUrl.substr(0, 4) == "www.") ? baseUrl.substr(4) : baseUrl; } } diff --git a/src/utils/location/isDomain.as b/src/utils/location/isDomain.as index 2a0e7ee..f10edfa 100644 --- a/src/utils/location/isDomain.as +++ b/src/utils/location/isDomain.as @@ -1,27 +1,27 @@ package utils.location { import flash.display.DisplayObject; /** - * Detects if MovieClip's embed location matches passed domain. + * Detects if MovieClip embed location matches passed domain. * Check for domain: * <pre> * trace(isDomain(_root, "google.com")); * trace(isDomain(_root, "bbc.co.uk")); * </pre> * You can even check for subdomains: * <pre> * trace(isDomain(_root, "subdomain.aaronclinger.com")) * </pre> * @param location MovieClip to compare location of * @param domain Web domain * @return true if file's embed location matched passed domain * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isDomain(location:DisplayObject, domain:String):Boolean { return getDomain(location).slice(-domain.length) == domain; } } diff --git a/src/utils/number/confine.as b/src/utils/number/confine.as index 3e26c33..dfa789f 100644 --- a/src/utils/number/confine.as +++ b/src/utils/number/confine.as @@ -1,14 +1,15 @@ -package utils.number -{ +package utils.number { + + + /** - * Resticts the <code>value</code> to the <code>min</code> and <code>max</code> + * Restricts the <code>value</code> to the <code>min</code> and <code>max</code> * @param value the number to restrict * @param min the minimum number for <code>value</code> to be - * @param max the maximmum number for <code>value</code> to be + * @param max the maximum number for <code>value</code> to be * @return */ - public function confine(value:Number, min:Number, max:Number):Number - { + public function confine(value:Number, min:Number, max:Number):Number { return value < min ? min : (value > max ? max : value); } -} \ No newline at end of file +} diff --git a/src/utils/number/format.as b/src/utils/number/format.as index 664018f..6da3a38 100644 --- a/src/utils/number/format.as +++ b/src/utils/number/format.as @@ -1,55 +1,50 @@ -package utils.number -{ +package utils.number { + + + /** - Formats a number. - - @param value: The number you wish to format. - @param minLength: The minimum length of the number. - @param thouDelim: The character used to seperate thousands. - @param fillChar: The leading character used to make the number the minimum length. - @return Returns the formated number as a String. - @example - <code> - trace(NumberUtil.format(1234567, 8, ",")); // Traces 01,234,567 - </code> + Formats a number. + @param value The number you wish to format. + @param minLength The minimum length of the number. + @param thouDelim The character used to separate thousands. + @param fillChar The leading character used to make the number the minimum length. + @return Returns the formatted number as a String. + @example + <code> + trace(NumberUtil.format(1234567, 8, ",")); // Traces 01,234,567 + </code> */ - public function format(value:Number, minLength:uint, thouDelim:String = null, fillChar:String = null):String - { + public function format(value:Number, minLength:uint, thouDelim:String = null, fillChar:String = null):String { var num:String = value.toString(); var len:uint = num.length; - if (thouDelim != null) - { + if(thouDelim != null) { var numSplit:Array = num.split(''); var counter:uint = 3; var i:uint = numSplit.length; - while (--i > 0) - { + while(--i > 0) { counter--; - if (counter == 0) - { + if(counter == 0) { counter = 3; numSplit.splice(i, 0, thouDelim); } } num = numSplit.join(''); } - if (minLength != 0) - { - if (len < minLength) - { + if(minLength != 0) { + if(len < minLength) { minLength -= len; var addChar:String = (fillChar == null) ? '0' : fillChar; - while (minLength--) + while(minLength--) num = addChar + num; } } return num; } -} \ No newline at end of file +} diff --git a/src/utils/number/getWeightedAverage.as b/src/utils/number/getWeightedAverage.as index 05392cd..1805b46 100644 --- a/src/utils/number/getWeightedAverage.as +++ b/src/utils/number/getWeightedAverage.as @@ -1,24 +1,22 @@ -package utils.number -{ +package utils.number { + + + /** - * Low pass filter alogrithm for easing a value toward a destination value. + * Low pass filter algorithm for easing a value toward a destination value. * Works best for tweening values when no definite time duration exists and * when the destination value changes. - * * When <code>(0.5 &lt; n &lt; 1)</code>, then the resulting values will * overshoot (ping-pong) until they reach the destination value. - * * When <code>n</code> is greater than 1, as its value increases, the time * it takes to reach the destination also increases. A pleasing value for * <code>n</code> is 5. - * * @param value The current value. * @param dest The destination value. * @param n The slowdown factor. * @return The weighted average. */ - public function getWeightedAverage(value:Number, dest:Number, n:Number):Number - { + public function getWeightedAverage(value:Number, dest:Number, n:Number):Number { return value + (dest - value) / n; } -} \ No newline at end of file +} diff --git a/src/utils/number/pad.as b/src/utils/number/pad.as index e0ff576..b2c3fac 100644 --- a/src/utils/number/pad.as +++ b/src/utils/number/pad.as @@ -1,76 +1,74 @@ -package utils.number -{ +package utils.number { + + + /** * Pads the <code>value</code> with the set number of digits before and after the point. * If the number of digits in the integer of <code>value</code> is less than <code>beforePoint</code>, the remaining digits are filled with zeros. - * If the number of digits in the decimal of <code>value</code> is less than <code>afterPoint</code>, the remaning digits are filled with zeros. + * If the number of digits in the decimal of <code>value</code> is less than <code>afterPoint</code>, the remaining digits are filled with zeros. * @param value the number to pad * @param beforePoint the number of digits to pad before the point * @param afterPoint the number of digits to pad after the point * @return <code>value</code> padded as a <code>String</code> * @example * <listing version="3.0"> * NumberUtil.pad(.824, 0, 5); // returns ".82400" * NumberUtil.pad(9, 3, 2); // returns "009.00" * NumberUtil.pad(2835.3, 4, 2); // returns "2835.30" * </listing> */ - public function pad(value:Number, beforePoint:uint, afterPoint:uint = 0):String - { + public function pad(value:Number, beforePoint:uint, afterPoint:uint = 0):String { // separate the integer from the decimal var valueArray:Array = String(value).split("."); var integer:String = valueArray[0]; // determine the sign of the value var negative:Boolean = integer.substr(0, 1) == "-"; // remove the "-" if it exists - if (negative) + if(negative) integer = integer.substr(1); // treat zeros as empty, so integer.length doesn't return 1 when integer is 0 - if (integer == "0") - { + if(integer == "0") { integer = ""; } var len:int = integer.length; // determine how many times "0" needs to be prepended var zeros:int = Math.max(0, beforePoint - len); // prepend "0" until zeros == 0 - while (zeros--) + while(zeros--) integer = "0" + integer; var decimal:String; // if a point didn't exist or the decimal is 0, empty the decimal - if (valueArray.length == 1 || valueArray[1] == "0") - { + if(valueArray.length == 1 || valueArray[1] == "0") { decimal = ""; } - else - { + else { decimal = valueArray[1]; } len = decimal.length; // determine how many times "0" needs to be appended zeros = Math.max(0, afterPoint - len); // append "0" until zeros == 0 - while (zeros--) + while(zeros--) decimal += "0"; // set sign if negative var sign:String = negative ? "-" : ""; // set point if a decimal exists (or afterPoint > 0, determined earlier) var point:String = decimal ? "." : ""; return sign + integer + point + decimal; } -} \ No newline at end of file +} diff --git a/src/utils/number/toHex.as b/src/utils/number/toHex.as index e19e09b..f20979a 100644 --- a/src/utils/number/toHex.as +++ b/src/utils/number/toHex.as @@ -1,38 +1,32 @@ -package utils.number -{ +package utils.number { + + + /** * Outputs the hex value of a int, allowing the developer to specify - * the endinaness in the process. Hex output is lowercase. - * + * the endian in the process. Hex output is lowercase. * @param n The int value to output as hex * @param bigEndian Flag to output the int as big or little endian * @return A string of length 8 corresponding to the * hex representation of n ( minus the leading "0x" ) * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function toHex(n:int, bigEndian:Boolean = false):String - { + public function toHex(n:int, bigEndian:Boolean = false):String { var s:String = ""; - if (bigEndian) - { - for (var i:int = 0; i < 4; i++) - { - s += hexChars.charAt((n >> ((3 - i) * 8 + 4)) & 0xF) - + hexChars.charAt((n >> ((3 - i) * 8)) & 0xF); + if(bigEndian) { + for(var i:int = 0; i < 4; i++) { + s += hexChars.charAt((n >> ((3 - i) * 8 + 4)) & 0xF) + hexChars.charAt((n >> ((3 - i) * 8)) & 0xF); } } - else - { - for (var x:int = 0; x < 4; x++) - { - s += hexChars.charAt((n >> (x * 8 + 4)) & 0xF) - + hexChars.charAt((n >> (x * 8)) & 0xF); + else { + for(var x:int = 0; x < 4; x++) { + s += hexChars.charAt((n >> (x * 8 + 4)) & 0xF) + hexChars.charAt((n >> (x * 8)) & 0xF); } } return s; } -} \ No newline at end of file +} diff --git a/src/utils/object/isEmpty.as b/src/utils/object/isEmpty.as index 4defaa0..39cb047 100644 --- a/src/utils/object/isEmpty.as +++ b/src/utils/object/isEmpty.as @@ -1,42 +1,41 @@ -package utils.object -{ +package utils.object { + + + /** - Determines if object contains no value(s). - - @param obj: Object to derimine if empty. - @return Returns <code>true</code> if object is empty; otherwise <code>false</code>. - @example - <code> - var testNumber:Number; - var testArray:Array = new Array(); - var testString:String = ""; - var testObject:Object = new Object(); - - trace(ObjectUtil.isEmpty(testNumber)); // traces "true" - trace(ObjectUtil.isEmpty(testArray)); // traces "true" - trace(ObjectUtil.isEmpty(testString)); // traces "true" - trace(ObjectUtil.isEmpty(testObject)); // traces "true" - </code> + Determines if object contains no value(s). + @param obj Object to determine if empty. + @return Returns <code>true</code> if object is empty; otherwise <code>false</code>. + @example + <code> + var testNumber:Number; + var testArray:Array = new Array(); + var testString:String = ""; + var testObject:Object = new Object(); + + trace(ObjectUtil.isEmpty(testNumber)); // traces "true" + trace(ObjectUtil.isEmpty(testArray)); // traces "true" + trace(ObjectUtil.isEmpty(testString)); // traces "true" + trace(ObjectUtil.isEmpty(testObject)); // traces "true" + </code> */ - public function isEmpty(obj:*):Boolean - { - if (obj == undefined) + public function isEmpty(obj:*):Boolean { + if(obj == undefined) return true; - if (obj is Number) + if(obj is Number) return isNaN(obj); - if (obj is Array || obj is String) + if(obj is Array || obj is String) return obj.length == 0; - if (obj is Object) - { - for (var prop:String in obj) + if(obj is Object) { + for(var prop:String in obj) return false; return true; } return false; } -} \ No newline at end of file +} diff --git a/src/utils/string/afterLast.as b/src/utils/string/afterLast.as index a00ce82..c6c2197 100644 --- a/src/utils/string/afterLast.as +++ b/src/utils/string/afterLast.as @@ -1,28 +1,28 @@ package utils.string { /** - * Returns everything after the last occurence of the provided character in value. + * Returns everything after the last occurrence of the provided character in value. * @param value Input String * @param ch Character or sub-string * @return Output String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function afterLast(value:String, ch:String):String { var out:String = ""; if(value) { var idx:int = value.lastIndexOf(ch); if(idx != -1) { idx += ch.length; out = value.substr(idx); } } return out; } } diff --git a/src/utils/string/beginsWith.as b/src/utils/string/beginsWith.as index 547b88e..d69d07c 100644 --- a/src/utils/string/beginsWith.as +++ b/src/utils/string/beginsWith.as @@ -1,20 +1,17 @@ -package utils.string -{ +package utils.string { + + + /** - * Determines whether the specified string begins with the spcified prefix. - * + * Determines whether the specified string begins with the specified prefix. * @param input The string that the prefix will be checked against. - * * @param prefix The prefix that will be tested against the string. - * * @returns True if the string starts with the prefix, false if it does not. - * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function beginsWith(input:String, prefix:String):Boolean - { + public function beginsWith(input:String, prefix:String):Boolean { return (prefix == input.substring(0, prefix.length)); } -} \ No newline at end of file +} diff --git a/src/utils/string/between.as b/src/utils/string/between.as index e46df6b..c8dbd10 100644 --- a/src/utils/string/between.as +++ b/src/utils/string/between.as @@ -1,34 +1,34 @@ package utils.string { /** - * Returns everything after the first occurance of begin and before the first occurrence of end in String. + * Returns everything after the first occurrence of begin and before the first occurrence of end in String. * @param value Input String * @param start Character or sub-string to use as the start index * @param end Character or sub-string to use as the end index - * @returns Everything after the first occurance of begin and before the first occurrence of end in String. + * @returns Everything after the first occurrence of begin and before the first occurrence of end in String. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function between(value:String, start:String, end:String):String { var out:String = ""; if(value) { var startIdx:int = value.indexOf(start); if(startIdx != -1) { startIdx += start.length; // RM: should we support multiple chars? (or ++startIdx); var endIdx:int = value.indexOf(end, startIdx); if(endIdx != -1) { out = value.substr(startIdx, endIdx - startIdx); } } } return out; } } diff --git a/src/utils/string/endsWith.as b/src/utils/string/endsWith.as index 726eb36..49bc710 100644 --- a/src/utils/string/endsWith.as +++ b/src/utils/string/endsWith.as @@ -1,20 +1,17 @@ -package utils.string -{ +package utils.string { + + + /** - * Determines whether the specified string ends with the spcified suffix. - * - * @param input The string that the suffic will be checked against. - * - * @param prefix The suffic that will be tested against the string. - * + * Determines whether the specified string ends with the specified suffix. + * @param input The string that the suffix will be checked against. + * @param suffix The suffix that will be tested against the string. * @returns True if the string ends with the suffix, false if it does not. - * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function endsWith(input:String, suffix:String):Boolean - { + public function endsWith(input:String, suffix:String):Boolean { return (suffix == input.substring(input.length - suffix.length)); } -} \ No newline at end of file +} diff --git a/src/utils/string/truncate2.as b/src/utils/string/truncate2.as index 38454f1..402f1f6 100644 --- a/src/utils/string/truncate2.as +++ b/src/utils/string/truncate2.as @@ -1,36 +1,36 @@ package utils.string { /** * Returns a String truncated to a specified length with optional suffix. * @param value Input String - * @param length Length the String should be shortend to + * @param length Length the String should be shortened to * @param suffix (optional, default="...") String to append to the end of the truncated String * @returns String String truncated to a specified length with optional suffix */ public function truncate2(value:String, length:uint, suffix:String = "..."):String { var out:String = ""; var l:uint = length; if(value) { l -= suffix.length; var trunc:String = value; if(trunc.length > l) { trunc = trunc.substr(0, l); if(/[^\s]/.test(value.charAt(l))) { trunc = rtrim(trunc.replace(/\w+$|\s+$/, "")); } trunc += suffix; } out = trunc; } return out; } } diff --git a/src/utils/string/wordCount.as b/src/utils/string/wordCount.as index 57faf65..8201ce0 100644 --- a/src/utils/string/wordCount.as +++ b/src/utils/string/wordCount.as @@ -1,22 +1,22 @@ package utils.string { /** - * Determins the number of words in a String. + * Determines the number of words in a String. * @param value Input String * @returns Number of words in a String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function wordCount(value:String):uint { var out:uint = 0; if(value) { out = value.match(/\b\w+\b/g).length; } return out; } } diff --git a/src/utils/string/xtrim.as b/src/utils/string/xtrim.as index d8c946f..a9f0f0a 100644 --- a/src/utils/string/xtrim.as +++ b/src/utils/string/xtrim.as @@ -1,23 +1,25 @@ -package utils.string -{ +package utils.string { + + + /** - * Extreme Trim: remove whitespace, line feeds, carrige returns from string + * Extreme Trim: remove whitespace, line feeds, carriage returns from string */ - public function xtrim(str:String = null):String - { + public function xtrim(str:String = null):String { str = (!str) ? "" : str; + var o:String = new String(); var TAB:Number = 9; var LINEFEED:Number = 10; var CARRIAGE:Number = 13; var SPACE:Number = 32; - for (var i:int = 0; i < str.length; i++) - { - if (str.charCodeAt(i) != SPACE && str.charCodeAt(i) != CARRIAGE && str.charCodeAt(i) != LINEFEED && str.charCodeAt(i) != TAB) - { + + for(var i:int = 0; i < str.length; i++) { + if(str.charCodeAt(i) != SPACE && str.charCodeAt(i) != CARRIAGE && str.charCodeAt(i) != LINEFEED && str.charCodeAt(i) != TAB) { o += str.charAt(i); } } + return o; } -} \ No newline at end of file +} diff --git a/src/utils/type/describeMethods.as b/src/utils/type/describeMethods.as index 13449ef..6a1ece2 100644 --- a/src/utils/type/describeMethods.as +++ b/src/utils/type/describeMethods.as @@ -1,19 +1,18 @@ -package utils.type -{ +package utils.type { + + + /** * Targeted reflection describing an object's methods. - * * @param value The object or class to introspect. * @param metadataType Optional filter to return only those - * method descritions containing the - * specified metadata. - * + * method descriptions containing the + * specified metadata. * @return A list of XML method descriptions. */ - public function describeMethods(value:Object, metadataType:String = null):XMLList - { + public function describeMethods(value:Object, metadataType:String = null):XMLList { var methods:XMLList = describeType(value).factory.method; return (metadataType == null) ? methods : methods.(child("metadata").(@name == metadataType).length() > 0); } -} \ No newline at end of file +} diff --git a/src/utils/type/describeProperties.as b/src/utils/type/describeProperties.as index 93a065a..6591a1b 100644 --- a/src/utils/type/describeProperties.as +++ b/src/utils/type/describeProperties.as @@ -1,20 +1,19 @@ -package utils.type -{ +package utils.type { + + + /** * Targeted reflection describing an object's properties, including both - * accessor's (getter/setters) and pure properties. - * + * accessor (getter/setters) and pure properties. * @param value The object or class to introspect. * @param metadataType Optional filter to return only those - * property descritions containing the - * specified metadata. - * + * property descriptions containing the + * specified metadata. * @return A list of XML property descriptions. */ - public function describeProperties(value:Object, metadataType:String = null):XMLList - { + public function describeProperties(value:Object, metadataType:String = null):XMLList { var properties:XMLList = describeType(value).factory.*.(localName() == "accessor" || localName() == "variable"); return (metadataType == null) ? properties : properties.(child("metadata").(@name == metadataType).length() > 0); } -} \ No newline at end of file +} diff --git a/src/utils/type/forInstance.as b/src/utils/type/forInstance.as index 588b5d0..729195d 100644 --- a/src/utils/type/forInstance.as +++ b/src/utils/type/forInstance.as @@ -1,24 +1,22 @@ -package utils.type -{ +package utils.type { import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; + + /** * Returns a <code>Class</code> object that corresponds with the given - * instance. If no correspoding class was found, a + * instance. If no corresponding class was found, a * <code>ClassNotFoundError</code> will be thrown. - * * @param instance the instance from which to return the class * @param applicationDomain the optional applicationdomain where the instance's class resides - * * @return the <code>Class</code> that corresponds with the given instance - * - * @see org.springextensions.actionscript.errors.ClassNotFoundError */ - public function forInstance(instance:*, applicationDomain:ApplicationDomain = null):Class - { + public function forInstance(instance:*, applicationDomain:ApplicationDomain = null):Class { applicationDomain = (applicationDomain == null) ? ApplicationDomain.currentDomain : applicationDomain; + var className:String = getQualifiedClassName(instance); + return forName(className, applicationDomain); } -} \ No newline at end of file +} diff --git a/src/utils/type/forName.as b/src/utils/type/forName.as index 5e794b3..925e375 100644 --- a/src/utils/type/forName.as +++ b/src/utils/type/forName.as @@ -1,49 +1,41 @@ -package utils.type -{ +package utils.type { import flash.system.ApplicationDomain; + + /** * Returns a <code>Class</code> object that corresponds with the given - * name. If no correspoding class was found in the applicationdomain tree, a + * name. If no corresponding class was found in the applicationdomain tree, a * <code>ClassNotFoundError</code> will be thrown. - * * @param name the name from which to return the class * @param applicationDomain the optional applicationdomain where the instance's class resides - * * @return the <code>Class</code> that corresponds with the given name - * - * @see org.springextensions.actionscript.errors.ClassNotFoundError */ - public function forName(name:String, applicationDomain:ApplicationDomain = null):Class - { + public function forName(name:String, applicationDomain:ApplicationDomain = null):Class { applicationDomain = (applicationDomain == null) ? ApplicationDomain.currentDomain : applicationDomain; + var result:Class; - if (!applicationDomain) - { + if(!applicationDomain) { applicationDomain = ApplicationDomain.currentDomain; } - while (!applicationDomain.hasDefinition(name)) - { - if (applicationDomain.parentDomain) - { + while(!applicationDomain.hasDefinition(name)) { + if(applicationDomain.parentDomain) { applicationDomain = applicationDomain.parentDomain; } - else - { + else { break; } } - try - { + try { result = applicationDomain.getDefinition(name) as Class; } - catch (e:ReferenceError) - { + catch (e:ReferenceError) { throw new Error("A class with the name '" + name + "' could not be found."); } + return result; } -} \ No newline at end of file +}
as3/as3-utils
7eb5c326c91e4238c994f5bed2abb5a71590df1f
hexChars from var to const. toHex() now accepts Endian.BIG_ENDIAN as well as bools.
diff --git a/src/utils/number/hexChars.as b/src/utils/number/hexChars.as index 378a471..1240b49 100644 --- a/src/utils/number/hexChars.as +++ b/src/utils/number/hexChars.as @@ -1,6 +1,6 @@ package utils.number { [ExcludeClass] /** String for quick lookup of a hex character based on index */ - public var hexChars:String = "0123456789abcdef"; + public const hexChars:String = "0123456789abcdef"; } \ No newline at end of file diff --git a/src/utils/number/toHex.as b/src/utils/number/toHex.as index e19e09b..5e072fd 100644 --- a/src/utils/number/toHex.as +++ b/src/utils/number/toHex.as @@ -1,38 +1,50 @@ package utils.number { + import flash.utils.Endian; + /** * Outputs the hex value of a int, allowing the developer to specify * the endinaness in the process. Hex output is lowercase. * * @param n The int value to output as hex - * @param bigEndian Flag to output the int as big or little endian + * @param endianness Flag to output the int as big or little endian. + * Can be Endian.BIG_INDIAN/Endian.LITTLE_ENDIAN or true/false * @return A string of length 8 corresponding to the * hex representation of n ( minus the leading "0x" ) + * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 - * @tiptext + * @see flash.utils.Endian + * + * @author Unknown. flash.utils.Endian tweak added by Mims Wright */ - public function toHex(n:int, bigEndian:Boolean = false):String + public function toHex(n:int, endianness:* = Endian.LITTLE_ENDIAN):String { + var bigEndian:Boolean; + if (endianness is Boolean) { + bigEndian = Boolean(endianness); + } else { + bigEndian = endianness == Endian.BIG_ENDIAN; + } var s:String = ""; if (bigEndian) { for (var i:int = 0; i < 4; i++) { s += hexChars.charAt((n >> ((3 - i) * 8 + 4)) & 0xF) + hexChars.charAt((n >> ((3 - i) * 8)) & 0xF); } } else { for (var x:int = 0; x < 4; x++) { s += hexChars.charAt((n >> (x * 8 + 4)) & 0xF) + hexChars.charAt((n >> (x * 8)) & 0xF); } } return s; } } \ No newline at end of file
as3/as3-utils
16c9e0c7c48845b7ef061090ccef51c56ee69720
Don't need the overhead of a try/catch to get the stack trace.
diff --git a/src/utils/error/getStackTrace.as b/src/utils/error/getStackTrace.as index ed417ca..da7537a 100644 --- a/src/utils/error/getStackTrace.as +++ b/src/utils/error/getStackTrace.as @@ -1,21 +1,12 @@ package utils.error { /** * Get a stack trace * @return A stack trace * @author Jackson Dunstan */ public function getStackTrace():String { - try - { - throw new Error(); - } - catch (err:Error) - { - return err.getStackTrace(); - } - // It's impossible to reach this - return null; + return new Error().getStackTrace(); } } \ No newline at end of file
as3/as3-utils
8027a9b52893cb0681daef1fa964a89451cf2869
Revert "clearFields fix."
diff --git a/src/utils/textField/clearFields.as b/src/utils/textField/clearFields.as index 276b078..dfac4ef 100644 --- a/src/utils/textField/clearFields.as +++ b/src/utils/textField/clearFields.as @@ -1,32 +1,28 @@ package utils.textField { import flash.display.DisplayObject; - import flash.display.DisplayObjectContainer; import flash.text.TextField; /** - * Clear a <code>TextField</code> text or to all <code>TextField</code>'s texts in a <code>DisplayObjectContainer</code>. + * Clear a <code>TextField</code> text or to all <code>TextField</code>'s texts in a <code>DisplayObject</code>. * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. */ public function clearFields(o:DisplayObject):void { - var tf:TextField; if (o is TextField) { - tf = o as TextField; + var tf:TextField = o as TextField; tf.text = tf.htmlText = ''; } - else if (o is DisplayObjectContainer) + else if (o is DisplayObject) { - var container:DisplayObjectContainer = o as DisplayObjectContainer; - for (var i:int = 0; i < container.numChildren; i++) + for (var i:String in o) { - if (container.getChildAt(i) is TextField) + if (o[i] is TextField) { - tf = container.getChildAt(i) as TextField; - tf.text = tf.htmlText = ''; + o[i].text = o[i].htmlText = ''; } } } } } \ No newline at end of file
as3/as3-utils
c7eb70a27929362455188bf5b2c35f6565d59550
styleFields fix.
diff --git a/src/utils/textField/styleFields.as b/src/utils/textField/styleFields.as index 50cb6b5..51d4973 100644 --- a/src/utils/textField/styleFields.as +++ b/src/utils/textField/styleFields.as @@ -1,34 +1,38 @@ package utils.textField { import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; import flash.text.StyleSheet; import flash.text.TextField; /** - * Apply the application stylesheet to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObject</code>. + * Apply the application stylesheet to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObjectContainer</code>. * * <p><b>Warning</b>: Unlike <code>formatFields</code> you must <i>reset</i> your <code>htmlText</code> to have the style applied.</p> * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. * @param stylesheet to apply to the <code>TextField</code>'s (Default: <code>App.css</code>). * @see sekati.core.App#css */ public function styleFields(o:DisplayObject, stylesheet:StyleSheet):void { + var tf:TextField; var css:StyleSheet = stylesheet; if (o is TextField) { - var tf:TextField = o as TextField; + tf = o as TextField; tf.styleSheet = css; } - else if (o is DisplayObject) + else if (o is DisplayObjectContainer) { - for (var i:String in o) + var container:DisplayObjectContainer = o as DisplayObjectContainer; + for (var i:int = 0; i < container.numChildren; i++) { - if (o[i] is TextField && !o[i].styleSheet) + if (container.getChildAt(i) is TextField) { - o[i].styleSheet = css; + tf = container.getChildAt(i) as TextField; + tf.styleSheet = css; } } } } } \ No newline at end of file
as3/as3-utils
ee1a749cee73e0f446138ab05b479170bda7565b
formatFields fix.
diff --git a/src/utils/textField/formatFields.as b/src/utils/textField/formatFields.as index 635a5e1..ba2e8c1 100644 --- a/src/utils/textField/formatFields.as +++ b/src/utils/textField/formatFields.as @@ -1,30 +1,34 @@ package utils.textField { import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; import flash.text.TextField; import flash.text.TextFormat; /** - * Apply a <code>TextFormat</code> to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObject</code>. + * Apply a <code>TextFormat</code> to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObjectContainer</code>. * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. * @param textFormat to apply to the <code>TextField</code>'s. */ public function formatFields(o:DisplayObject, textFormat:TextFormat):void { + var tf:TextField; if (o is TextField) { - var tf:TextField = o as TextField; + tf = o as TextField; tf.setTextFormat(textFormat); } - else if (o is DisplayObject) + else if (o is DisplayObjectContainer) { - for (var i:String in o) + var container:DisplayObjectContainer = o as DisplayObjectContainer; + for (var i:int = 0; i < container.numChildren; i++) { - if (o[i] is TextField && !o[i].styleSheet) + if (container.getChildAt(i) is TextField) { - o[i].setTextFormat(textFormat); + tf = container.getChildAt(i) as TextField; + tf.setTextFormat(textFormat); } } } } } \ No newline at end of file
as3/as3-utils
d7b456b184d3a0681b2566958c4c7db511fbeb06
clearFields fix.
diff --git a/src/utils/textField/clearFields.as b/src/utils/textField/clearFields.as index dfac4ef..276b078 100644 --- a/src/utils/textField/clearFields.as +++ b/src/utils/textField/clearFields.as @@ -1,28 +1,32 @@ package utils.textField { import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; import flash.text.TextField; /** - * Clear a <code>TextField</code> text or to all <code>TextField</code>'s texts in a <code>DisplayObject</code>. + * Clear a <code>TextField</code> text or to all <code>TextField</code>'s texts in a <code>DisplayObjectContainer</code>. * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. */ public function clearFields(o:DisplayObject):void { + var tf:TextField; if (o is TextField) { - var tf:TextField = o as TextField; + tf = o as TextField; tf.text = tf.htmlText = ''; } - else if (o is DisplayObject) + else if (o is DisplayObjectContainer) { - for (var i:String in o) + var container:DisplayObjectContainer = o as DisplayObjectContainer; + for (var i:int = 0; i < container.numChildren; i++) { - if (o[i] is TextField) + if (container.getChildAt(i) is TextField) { - o[i].text = o[i].htmlText = ''; + tf = container.getChildAt(i) as TextField; + tf.text = tf.htmlText = ''; } } } } } \ No newline at end of file
as3/as3-utils
b8bc32c0e025cfbb8ef432b73609d97c7963fc68
Deprecated constrain and confine and kept clamp. Cleaned up references to them. Updated documentation to lots of the files. Added additional functionality to addLeadingZero(es).
diff --git a/src/deprecated/confine.as b/src/deprecated/confine.as new file mode 100644 index 0000000..d9776e9 --- /dev/null +++ b/src/deprecated/confine.as @@ -0,0 +1,16 @@ +package deprecated +{ + [Deprecated(replacement="utils.number.clamp")] + + /** + * Resticts the <code>value</code> to the <code>min</code> and <code>max</code> + * @param value the number to restrict + * @param min the minimum number for <code>value</code> to be + * @param max the maximmum number for <code>value</code> to be + * @return + */ + public function confine(value:Number, min:Number, max:Number):Number + { + return value < min ? min : (value > max ? max : value); + } +} \ No newline at end of file diff --git a/src/deprecated/constrain.as b/src/deprecated/constrain.as new file mode 100644 index 0000000..3e08fcd --- /dev/null +++ b/src/deprecated/constrain.as @@ -0,0 +1,23 @@ +package deprecated +{ + [Deprecated(replacement="utils.number.clamp")] + + /** + Determines if value falls within a range; if not it is snapped to the nearest range value. + + @param value: Number to determine if it is included in the range. + @param firstValue: First value of the range. + @param secondValue: Second value of the range. + @return Returns either the number as passed, or its value once snapped to nearest range value. + @usageNote The constraint values do not need to be in order. + @example + <code> + trace(NumberUtil.constrain(3, 0, 5)); // Traces 3 + trace(NumberUtil.constrain(7, 0, 5)); // Traces 5 + </code> + */ + public function constrain(value:Number, firstValue:Number, secondValue:Number):Number + { + return Math.min(Math.max(value, Math.min(firstValue, secondValue)), Math.max(firstValue, secondValue)); + } +} \ No newline at end of file diff --git a/src/utils/date/formatDate.as b/src/utils/date/formatDate.as index cca4465..36a8fee 100644 --- a/src/utils/date/formatDate.as +++ b/src/utils/date/formatDate.as @@ -1,409 +1,409 @@ package utils.date { import utils.conversion.minutesToSeconds; - import utils.number.addLeadingZero; + import utils.number.addLeadingZeroes; import utils.number.format; import utils.number.getOrdinalSuffix; /** * Formats a Date object for display. Acts almost identically to the PHP date() function. * You can prevent a recognized character in the format string from being expanded by escaping it with a preceding ^. * <table border="1"> * <tr> * <th style="width:150px;">Format character</th> * <th>Description</th> * <th style="width:200px;">Example returned values</th> * </tr> * <tr> * <td>d</td> * <td>Day of the month, 2 digits with leading zeros.</td> * <td>01 to 31</td> * </tr> * <tr> * <td>D</td> * <td>A textual representation of a day, three letters.</td> * <td>Mon through Sun</td> * </tr> * <tr> * <td>j</td> * <td>Day of the month without leading zeros.</td> * <td>1 to 31</td> * </tr> * <tr> * <td>l</td> * <td>A full textual representation of the day of the week.</td> * <td>Sunday through Saturday</td> * </tr> * <tr> * <td>N</td> * <td>ISO-8601 numeric representation of the day of the week.</td> * <td>1 (for Monday) through 7 (for Sunday)</td> * </tr> * <tr> * <td>S</td> * <td>English ordinal suffix for the day of the month, 2 characters.</td> * <td>st, nd, rd or th</td> * </tr> * <tr> * <td>w</td> * <td>Numeric representation of the day of the week.</td> * <td>0 (for Sunday) through 6 (for Saturday)</td> * </tr> * <tr> * <td>z</td> * <td>The day of the year (starting from 0).</td> * <td>0 through 365</td> * </tr> * <tr> * <td>W</td> * <td>ISO-8601 week number of year, weeks starting on Monday.</td> * <td>Example: 42 (the 42nd week in the year)</td> * </tr> * <tr> * <td>F</td> * <td>A full textual representation of a month, such as January or March.</td> * <td>January through December</td> * </tr> * <tr> * <td>m</td> * <td>Numeric representation of a month, with leading zeros.</td> * <td>01 through 12</td> * </tr> * <tr> * <td>M</td> * <td>A short textual representation of a month, three letters.</td> * <td>Jan through Dec</td> * </tr> * <tr> * <td>n</td> * <td>Numeric representation of a month, without leading zeros.</td> * <td>1 through 12</td> * </tr> * <tr> * <td>t</td> * <td>Number of days in the given month.</td> * <td>28 through 31</td> * </tr> * <tr> * <td>L</td> * <td>Determines if it is a leap year.</td> * <td>1 if it is a leap year, 0 otherwise</td> * </tr> * <tr> * <td>o or Y</td> * <td>A full numeric representation of a year, 4 digits.</td> * <td>Examples: 1999 or 2003</td> * </tr> * <tr> * <td>y</td> * <td>A two digit representation of a year.</td> * <td>Examples: 99 or 03</td> * </tr> * <tr> * <td>a</td> * <td>Lowercase Ante meridiem and Post meridiem.</td> * <td>am or pm</td> * </tr> * <tr> * <td>A</td> * <td>Uppercase Ante meridiem and Post meridiem.</td> * <td>AM or PM</td> * </tr> * <tr> * <td>B</td> * <td>Swatch Internet time.</td> * <td>000 through 999</td> * </tr> * <tr> * <td>g</td> * <td>12-hour format of an hour without leading zeros.</td> * <td>1 through 12</td> * </tr> * <tr> * <td>G</td> * <td>24-hour format of an hour without leading zeros.</td> * <td>0 through 23</td> * </tr> * <tr> * <td>h</td> * <td>12-hour format of an hour with leading zeros.</td> * <td>01 through 12</td> * </tr> * <tr> * <td>H</td> * <td>24-hour format of an hour with leading zeros.</td> * <td>00 through 23</td> * </tr> * <tr> * <td>i</td> * <td>Minutes with leading zeros.</td> * <td>00 to 59</td> * </tr> * <tr> * <td>s</td> * <td>Seconds, with leading zeros.</td> * <td>00 through 59</td> * </tr> * <tr> * <td>I</td> * <td>Determines if the date is in daylight saving time.</td> * <td>1 if Daylight Saving Time, 0 otherwise</td> * </tr> * <tr> * <td>O</td> * <td>Difference to coordinated universal time (UTC) in hours.</td> * <td>Example: +0200</td> * </tr> * <tr> * <td>P</td> * <td>Difference to Greenwich time (GMT/UTC) in hours with colon between hours and minutes.</td> * <td>Example: +02:00</td> * </tr> * <tr> * <td>e or T</td> * <td>Timezone abbreviation.</td> * <td>Examples: EST, MDT</td> * </tr> * <tr> * <td>Z</td> * <td>Timezone offset in seconds.</td> * <td>-43200 through 50400</td> * </tr> * <tr> * <td>c</td> * <td>ISO 8601 date.</td> * <td>2004-02-12T15:19:21+00:00</td> * </tr> * <tr> * <td>r</td> * <td>RFC 2822 formatted date.</td> * <td>Example: Thu, 21 Dec 2000 16:01:07 +0200</td> * </tr> * <tr> * <td>U</td> * <td>Seconds since the Unix Epoch.</td> * <td>Example: 1171479314</td> * </tr> * </table> * Example code: * <pre> * trace(DateUtils.formatDate(new Date(), "l ^t^h^e dS ^of F Y h:i:s A")); * </pre> * @param dateToFormat Date object you wish to format * @param formatString Format of the outputted date String. See the format characters options above. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function formatDate(dateToFormat:Date, formatString:String):String { var out:String = ""; var c:String; var i:int = -1; var l:uint = formatString.length; var t:Number; while(++i < l) { c = formatString.substr(i, 1); if(c == "^") { out += formatString.substr(++i, 1); } else { switch(c) { case "d" : // Day of the month, 2 digits with leading zeros - out += addLeadingZero(dateToFormat.getDate()); + out += addLeadingZeroes(dateToFormat.getDate()); break; case "D" : // A textual representation of a day, three letters out += getDayAbbrName(dateToFormat.getDay()); break; case "j" : // Day of the month without leading zeros out += String(dateToFormat.getDate()); break; case "l" : // A full textual representation of the day of the week out += getDayAsString(dateToFormat.getDay()); break; case "N" : // ISO-8601 numeric representation of the day of the week t = dateToFormat.getDay(); if(t == 0) t = 7; out += String(t); break; case "S" : // English ordinal suffix for the day of the month, 2 characters out += getOrdinalSuffix(dateToFormat.getDate()); break; case "w" : // Numeric representation of the day of the week out += String(dateToFormat.getDay()); break; case "z" : // The day of the year (starting from 0) - out += String(addLeadingZero(getDayOfTheYear(dateToFormat))); + out += String(addLeadingZeroes(getDayOfTheYear(dateToFormat))); break; case "W" : // ISO-8601 week number of year, weeks starting on Monday - out += String(addLeadingZero(getWeekOfTheYear(dateToFormat))); + out += String(addLeadingZeroes(getWeekOfTheYear(dateToFormat))); break; case "F" : // A full textual representation of a month, such as January or March out += getMonthName(dateToFormat.getMonth()); break; case "m" : // Numeric representation of a month, with leading zeros - out += addLeadingZero(dateToFormat.getMonth() + 1); + out += addLeadingZeroes(dateToFormat.getMonth() + 1); break; case "M" : // A short textual representation of a month, three letters out += getMonthAbbrName(dateToFormat.getMonth()); break; case "n" : // Numeric representation of a month, without leading zeros out += String((dateToFormat.getMonth() + 1)); break; case "t" : // Number of days in the given month out += String(getDaysInMonth(dateToFormat.getMonth(), dateToFormat.getFullYear())); break; case "L" : // Whether it is a leap year out += (isLeapYear(dateToFormat.getFullYear())) ? "1" : "0"; break; case "o" : case "Y" : // A full numeric representation of a year, 4 digits out += String(dateToFormat.getFullYear()); break; case "y" : // A two digit representation of a year out += String(dateToFormat.getFullYear()).substr(-2); break; case "a" : // Lowercase Ante meridiem and Post meridiem out += getMeridiem(dateToFormat.getHours()).toLowerCase(); break; case "A" : // Uppercase Ante meridiem and Post meridiem out += getMeridiem(dateToFormat.getHours()); break; case "B" : // Swatch Internet time out += format(getInternetTime(dateToFormat), 3, null, "0"); break; case "g" : // 12-hour format of an hour without leading zeros t = dateToFormat.getHours(); if(t == 0) { t = 12; } else if(t > 12) { t -= 12; } out += String(t); break; case "G" : // 24-hour format of an hour without leading zeros out += String(dateToFormat.getHours()); break; case "h" : // 12-hour format of an hour with leading zeros t = dateToFormat.getHours() + 1; if(t == 0) { t = 12; } else if(t > 12) { t -= 12; } - out += addLeadingZero(t); + out += addLeadingZeroes(t); break; case "H" : // 24-hour format of an hour with leading zeros - out += addLeadingZero(dateToFormat.getHours()); + out += addLeadingZeroes(dateToFormat.getHours()); break; case "i" : // Minutes with leading zeros - out += addLeadingZero(dateToFormat.getMinutes()); + out += addLeadingZeroes(dateToFormat.getMinutes()); break; case "s" : // Seconds, with leading zeros - out += addLeadingZero(dateToFormat.getSeconds()); + out += addLeadingZeroes(dateToFormat.getSeconds()); break; case "I" : // Whether or not the date is in daylights savings time out += (isDaylightSavings(dateToFormat)) ? "1" : "0"; break; case "O" : // Difference to Greenwich time (GMT/UTC) in hours out += getFormattedDifferenceFromUTC(dateToFormat); break; case "P" : out += getFormattedDifferenceFromUTC(dateToFormat, ":"); break; case "e" : case "T" : // Timezone identifier out += getTimezone(dateToFormat); break; case "Z" : // Timezone offset (GMT/UTC) in seconds. out += String(int(minutesToSeconds(dateToFormat.getTimezoneOffset()))); break; case "c" : // ISO 8601 date - out += dateToFormat.getFullYear() + "-" + addLeadingZero(dateToFormat.getMonth() + 1) + "-" + addLeadingZero(dateToFormat.getDate()) + "T" + addLeadingZero(dateToFormat.getHours()) + ":" + addLeadingZero(dateToFormat.getMinutes()) + ":" + addLeadingZero(dateToFormat.getSeconds()) + getFormattedDifferenceFromUTC(dateToFormat, ":"); + out += dateToFormat.getFullYear() + "-" + addLeadingZeroes(dateToFormat.getMonth() + 1) + "-" + addLeadingZeroes(dateToFormat.getDate()) + "T" + addLeadingZeroes(dateToFormat.getHours()) + ":" + addLeadingZeroes(dateToFormat.getMinutes()) + ":" + addLeadingZeroes(dateToFormat.getSeconds()) + getFormattedDifferenceFromUTC(dateToFormat, ":"); break; case "r" : // RFC 2822 formatted date - out += getDayAbbrName(dateToFormat.getDay()) + ", " + dateToFormat.getDate() + " " + getMonthAbbrName(dateToFormat.getMonth()) + " " + dateToFormat.getFullYear() + " " + addLeadingZero(dateToFormat.getHours()) + ":" + addLeadingZero(dateToFormat.getMinutes()) + ":" + addLeadingZero(dateToFormat.getSeconds()) + " " + getFormattedDifferenceFromUTC(dateToFormat); + out += getDayAbbrName(dateToFormat.getDay()) + ", " + dateToFormat.getDate() + " " + getMonthAbbrName(dateToFormat.getMonth()) + " " + dateToFormat.getFullYear() + " " + addLeadingZeroes(dateToFormat.getHours()) + ":" + addLeadingZeroes(dateToFormat.getMinutes()) + ":" + addLeadingZeroes(dateToFormat.getSeconds()) + " " + getFormattedDifferenceFromUTC(dateToFormat); break; case "U" : // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) t = int(dateToFormat.getTime() / 1000); out += String(t); break; default : out += formatString.substr(i, 1); } } } return out; } } diff --git a/src/utils/date/getFormattedDifferenceFromUTC.as b/src/utils/date/getFormattedDifferenceFromUTC.as index fa932cb..2329100 100644 --- a/src/utils/date/getFormattedDifferenceFromUTC.as +++ b/src/utils/date/getFormattedDifferenceFromUTC.as @@ -1,18 +1,18 @@ package utils.date { import utils.conversion.minutesToHours; - import utils.number.addLeadingZero; + import utils.number.addLeadingZeroes; /** * Formats the difference to coordinated undefined time (UTC). * @param date Date object to find the time zone offset of * @param separator Character(s) that separates the hours from minutes * @return Formatted time difference from UTC */ public function getFormattedDifferenceFromUTC(date:Date, separator:String = ""):String { var pre:String = (-date.getTimezoneOffset() < 0) ? "-" : "+"; - return pre + addLeadingZero(Math.floor(minutesToHours(date.getTimezoneOffset()))) + separator + addLeadingZero(date.getTimezoneOffset() % 60); + return pre + addLeadingZeroes(Math.floor(minutesToHours(date.getTimezoneOffset()))) + separator + addLeadingZeroes(date.getTimezoneOffset() % 60); } } diff --git a/src/utils/display/bringForward.as b/src/utils/display/bringForward.as index c2127d5..b0cc336 100644 --- a/src/utils/display/bringForward.as +++ b/src/utils/display/bringForward.as @@ -1,25 +1,25 @@ package utils.display { import flash.display.DisplayObject; - - import utils.number.confine; + + import utils.number.clamp; /** * Brings the DisplayObject forward in the display list. The <code>steps</code> parameter can be used to jump more than one level. * @param object the DisplayObject to reorder * @param steps the number of levels bring the DisplayObject forward * @return the new index of the DisplayObject */ public function bringForward(object:DisplayObject, steps:uint = 1):int { if (!object.parent) return -1; var index:int = object.parent.getChildIndex(object) + steps; - index = confine(index, 0, object.parent.numChildren - 1); + index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } \ No newline at end of file diff --git a/src/utils/display/bringToFront.as b/src/utils/display/bringToFront.as index f5d0352..f368901 100644 --- a/src/utils/display/bringToFront.as +++ b/src/utils/display/bringToFront.as @@ -1,25 +1,25 @@ package utils.display { import flash.display.DisplayObject; - import utils.number.confine; + import utils.number.clamp /** * Brings the DisplayObject to the front of the display list. The <code>back</code> parameter can be used to pull the DisplayObject back a few levels from the front. * @param object the DisplayObject to reorder * @param back the number of levels from the front of the display list * @return the new index of the DisplayObject */ public function bringToFront(object:DisplayObject, back:uint = 0):int { if (!object.parent) return -1; var index:int = object.parent.numChildren - (back + 1); - index = confine(index, 0, object.parent.numChildren - 1); + index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } \ No newline at end of file diff --git a/src/utils/display/sendBackward.as b/src/utils/display/sendBackward.as index 5282df7..9d3e23b 100644 --- a/src/utils/display/sendBackward.as +++ b/src/utils/display/sendBackward.as @@ -1,25 +1,26 @@ package utils.display { + import flash.display.DisplayObject; - - import utils.number.confine; + + import utils.number.clamp; /** * Sends the DisplayObject back in the display list. The <code>steps</code> parameter can be used to jump more than one level. * @param object the DisplayObject to reorder * @param steps the number of levels send the DisplayObject backward * @return the new index of the DisplayObject */ public function sendBackward(object:DisplayObject, steps:uint = 1):int { if (!object.parent) return -1; var index:int = object.parent.getChildIndex(object) - steps; - index = confine(index, 0, object.parent.numChildren - 1); + index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } \ No newline at end of file diff --git a/src/utils/display/sendToBack.as b/src/utils/display/sendToBack.as index d8ee272..3f2cad6 100644 --- a/src/utils/display/sendToBack.as +++ b/src/utils/display/sendToBack.as @@ -1,24 +1,25 @@ package utils.display { import flash.display.DisplayObject; + + import utils.number.clamp; - import utils.number.confine; /** * Sends the DisplayObject to the back of the display list. The <code>forward</code> parameter can be used to bring the DisplayObject forward a few levels from the back. * @param object the DisplayObject to reorder * @param forward the number of levels from the back of the display list * @return the new index of the DisplayObject */ public function sendToBack(object:DisplayObject, forward:uint = 0):int { if (!object.parent) return -1; - var index:int = confine(forward, 0, object.parent.numChildren - 1); + var index:int = clamp(forward, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } \ No newline at end of file diff --git a/src/utils/geom/getRectangleCenter.as b/src/utils/geom/getRectangleCenter.as index cb781ca..84f2662 100644 --- a/src/utils/geom/getRectangleCenter.as +++ b/src/utils/geom/getRectangleCenter.as @@ -1,14 +1,15 @@ package utils.geom { import flash.geom.Point; import flash.geom.Rectangle; - - + //TODO: Author? + /** * Calculates center Point of a Rectangle. + * * @param value Rectangle to determine center Point of */ public function getRectangleCenter(value:Rectangle):Point { return new Point(value.x + (value.width / 2), value.y + (value.height / 2)); } } diff --git a/src/utils/geom/reverseRectangle.as b/src/utils/geom/reverseRectangle.as index 2af2f0e..6e0b246 100644 --- a/src/utils/geom/reverseRectangle.as +++ b/src/utils/geom/reverseRectangle.as @@ -1,14 +1,17 @@ package utils.geom { import flash.geom.Rectangle; + // TODO: What's the point of this? Does this even work? Can a rect have a negative width or height? + // TODO: Author? /** * Reverse a rectangle. + * * @param value Source rectangle * @return Reversed rectangle */ public function reverseRectangle(value:Rectangle):Rectangle { return new Rectangle(value.left, value.top, -value.width, -value.height); } } diff --git a/src/utils/geom/roundPoint.as b/src/utils/geom/roundPoint.as index ee91837..0a3a500 100644 --- a/src/utils/geom/roundPoint.as +++ b/src/utils/geom/roundPoint.as @@ -1,14 +1,15 @@ package utils.geom { import flash.geom.Point; - + // todo: author? /** - * Rounds x and y of a Point. - * @param value Source Point to be rounded - * @return Rounded Point + * Returns a new point with x and y values rounded down to the nearest int. + * + * @param value Source Point to be rounded. + * @return Point A new point with x and y rounded down to an int. */ - public function roundPoint(value:Point):Point { - return new Point(int(value.x), int(value.y)); + public function roundPoint(point:Point):Point { + return new Point(int(point.x), int(point.y)); } } diff --git a/src/utils/geom/simplifyAngle.as b/src/utils/geom/simplifyAngle.as index 911af54..8445e10 100644 --- a/src/utils/geom/simplifyAngle.as +++ b/src/utils/geom/simplifyAngle.as @@ -1,21 +1,21 @@ package utils.geom { /** * Simplifys the supplied angle to its simpliest representation. * Example code: * <pre> * var simpAngle:Number = simplifyAngle(725); // returns 5 * var simpAngle2:Number = simplifyAngle(-725); // returns -5 * </pre> - * @param value Angle to simplify + * @param value Angle to simplify in degrees * @return Supplied angle simplified * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ - public function simplifyAngle(value:Number):Number { - var _rotations:Number = Math.floor(value / 360); + public function simplifyAngle(angle:Number):Number { + var _rotations:Number = Math.floor(angle / 360); - return (value >= 0) ? value - (360 * _rotations) : value + (360 * _rotations); + return (angle >= 0) ? angle - (360 * _rotations) : angle + (360 * _rotations); } } diff --git a/src/utils/load/calculateBufferPercent.as b/src/utils/load/calculateBufferPercent.as index b697f1b..b8fcab4 100644 --- a/src/utils/load/calculateBufferPercent.as +++ b/src/utils/load/calculateBufferPercent.as @@ -1,23 +1,23 @@ package utils.load { import utils.math.Percent; - import utils.number.constrain; + import utils.number.clamp; /** Calculates the percent the video has buffered. @param bytesLoaded: Number of bytes that have loaded between <code>startTime</code> and <code>elapsedTime</code>. @param bytesTotal: Number of bytes total to be loaded. @param startTime: Time in milliseconds when the load started. @param elapsedTime: The current time in milliseconds or time when load completed. @param lengthInMilliseconds: The total duration/length of the video in milliseconds. @return The percent buffered. */ public function calculateBufferPercent(bytesLoaded:uint, bytesTotal:uint, startTime:uint, elapsedTime:uint, lengthInMilliseconds:uint):Percent { var totalWait:Number = bytesTotal / (bytesLoaded / (elapsedTime - startTime)) - lengthInMilliseconds; var millisecondsRemaining:uint = calculateMillisecondsUntilBuffered(bytesLoaded, bytesTotal, startTime, elapsedTime, lengthInMilliseconds); - return (totalWait == Number.POSITIVE_INFINITY) ? new Percent(0) : new Percent(constrain(1 - millisecondsRemaining / totalWait, 0, 1)); + return (totalWait == Number.POSITIVE_INFINITY) ? new Percent(0) : new Percent(clamp(1 - millisecondsRemaining / totalWait, 0, 1)); } } \ No newline at end of file diff --git a/src/utils/number/addLeadingZeroes.as b/src/utils/number/addLeadingZeroes.as new file mode 100644 index 0000000..094f8d9 --- /dev/null +++ b/src/utils/number/addLeadingZeroes.as @@ -0,0 +1,34 @@ +package utils.number +{ + /** + * Formats a number to include one or more leading zeroes if needed. + * @example <listing version="3.0"> + * addLeadingZeroes(4); // "04" + * addLeadingZeroes(5, 3); // "0005" + * addLeadingZeroes(10, 1); // "10" + * addLeadingZeroes(10, 2); // "010" + * </listing> + * + * @param n The number that will be formatted. Ignores negative numbers. + * @return A string of the number with leading zeroes. + * + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * + * @author updated by Mims Wright - original contributor unknown + */ + public function addLeadingZeroes(n:Number, zeroes:int = 1):String + { + var out:String = String(n); + + if (n < 0 || zeroes < 1) { + return out; + } + + while (out.length < zeroes + 1) { + out = "0" + out; + } + + return out; + } +} \ No newline at end of file diff --git a/src/utils/number/clamp.as b/src/utils/number/clamp.as index fe29263..30c3d45 100644 --- a/src/utils/number/clamp.as +++ b/src/utils/number/clamp.as @@ -1,18 +1,18 @@ package utils.number { /** - * Clamp constrains a value to the defined numeric boundaries. + * Constrains a value to the defined numeric boundaries. + * * @example <listing version="3.0"> - * val: 20, 2 to 5 this will give back 5 since 5 is the top boundary - * val: 3, 2 to 5 this will give back 3 + * clamp(3, 2, 5); // this will give back 3 since it's within the range + * clamp(20, 2, 5); // this will give back 5 since 5 is the upper boundary + * clamp(-5, 2, 5); // this will give back 2 since 2 is the lower boundary * </listing> + * + * @author Mims Wright */ public function clamp(val:Number, min:Number, max:Number):Number { - if (val < min) - return min; - if (val > max) - return max; - return val; + return Math.max(Math.min(val, max), min); } } \ No newline at end of file
as3/as3-utils
3966781f29568ecafd23f2dc0de93892ac9e4794
added libs to integrate
diff --git a/Libraries to integrate.md b/Libraries to integrate.md new file mode 100644 index 0000000..64588b4 --- /dev/null +++ b/Libraries to integrate.md @@ -0,0 +1,3 @@ +* Sekati - [http://code.google.com/p/sekati/](http://code.google.com/p/sekati/) +* BumpSlide - [http://code.google.com/p/bumpslide/](http://code.google.com/p/bumpslide/) +* as3MathLib - [http://code.google.com/p/as3mathlib/](http://code.google.com/p/as3mathlib/) \ No newline at end of file
as3/as3-utils
c40227e4f6112e6f3f66e67714c0d262a33ad183
added Side
diff --git a/src/utils/geom/Side.as b/src/utils/geom/Side.as new file mode 100644 index 0000000..b44c48b --- /dev/null +++ b/src/utils/geom/Side.as @@ -0,0 +1,17 @@ +package utils.geom +{ + /** + * An enumeration of the four sides of a rectangle. + * Useful for working with tile engines, creating borders, etc. + */ + public class Side + { + public static const TOP:int = 1; + public static const BOTTOM:int = 2; + public static const LEFT:int = 4; + public static const RIGHT:int = 8; + + public static const NONE:int = 0; + public static const ALL:int = TOP | BOTTOM | LEFT | RIGHT; + } +} \ No newline at end of file
as3/as3-utils
d44b4922a0c84d0fa46dcd2450fa0b7989a6d4fa
fixed bug in duplicate display object
diff --git a/src/utils/display/duplicateDisplayObject.as b/src/utils/display/duplicateDisplayObject.as index 05e4caa..73f0680 100644 --- a/src/utils/display/duplicateDisplayObject.as +++ b/src/utils/display/duplicateDisplayObject.as @@ -1,54 +1,63 @@ package utils.display { import flash.display.DisplayObject; + import flash.display.Graphics; import flash.geom.Rectangle; import flash.system.Capabilities; - - // version check for scale9Grid bug + + import spark.primitives.Graphic; /** * duplicateDisplayObject * creates a duplicate of the DisplayObject passed. * similar to duplicateMovieClip in AVM1. If using Flash 9, make sure * you export for ActionScript the symbol you are duplicating - * @param target the display object to duplicate + * + * @param source the display object to duplicate * @param autoAdd if true, adds the duplicate to the display list - * in which target was located - * @return a duplicate instance of target + * in which source was located + * @return a duplicate instance of source + * + * @author Trevor McCauley - www.senocular.com + * @author cleaned up by Mims Wright */ - public function duplicateDisplayObject(target:DisplayObject, autoAdd:Boolean = false):DisplayObject + public function duplicateDisplayObject(source:DisplayObject, autoAdd:Boolean = false):DisplayObject { - var targetClass:Class = Object(target).constructor; - var duplicate:DisplayObject = new targetClass() as DisplayObject; + var sourceClass:Class = Object(source).constructor; + var duplicate:DisplayObject = new sourceClass() as DisplayObject; // duplicate properties - duplicate.transform = target.transform; - duplicate.filters = target.filters; - duplicate.cacheAsBitmap = target.cacheAsBitmap; - duplicate.opaqueBackground = target.opaqueBackground; - if (target.scale9Grid) + duplicate.transform = source.transform; + duplicate.filters = source.filters; + duplicate.cacheAsBitmap = source.cacheAsBitmap; + duplicate.opaqueBackground = source.opaqueBackground; + if (source.scale9Grid) { - var rect:Rectangle = target.scale9Grid; + var rect:Rectangle = source.scale9Grid; + // version check for scale9Grid bug if (Capabilities.version.split(" ")[1] == "9,0,16,0") { // Flash 9 bug where returned scale9Grid as twips rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20; } duplicate.scale9Grid = rect; } - // Flash 10 only - // duplicate.graphics.copyFrom(target.graphics); + // todo: needs test + if ("graphics" in source) { + var graphics:Graphics = Graphics(source["graphics"]); + Graphics(duplicate["graphics"]).copyFrom(graphics); + } // add to target parent's display list // if autoAdd was provided as true - if (autoAdd && target.parent) + if (autoAdd && source.parent) { - target.parent.addChild(duplicate); + source.parent.addChild(duplicate); } return duplicate; } } \ No newline at end of file
as3/as3-utils
a3a616b34005b6a1b14fd3181de1282e3e0dbe9c
Added getURL() from senocular and added some author tags for his stuff.
diff --git a/src/utils/net/getURL.as b/src/utils/net/getURL.as new file mode 100644 index 0000000..06eeefa --- /dev/null +++ b/src/utils/net/getURL.as @@ -0,0 +1,23 @@ +package utils.net +{ + import flash.net.URLRequest; + import flash.net.navigateToURL; + + /** + * getURL for ActionScript 3.0. Similar + * to getURL of ActionScript 2.0 in simplicity + * and ease. Errors are suppressed and traced + * to the output window. + * + * @author Trevor McCauley - www.senocular.com + */ + public function getURL(url:String, target:String = null):void { + + try { + navigateToURL(new URLRequest(url), target); + }catch(error:Error){ + trace("[getURL] "+error); + } + + } +} \ No newline at end of file diff --git a/src/utils/swf/SWFReader.as b/src/utils/swf/SWFReader.as index 7a31e65..5e80826 100644 --- a/src/utils/swf/SWFReader.as +++ b/src/utils/swf/SWFReader.as @@ -1,525 +1,527 @@ package utils.swf { import flash.display.ActionScriptVersion; import flash.geom.*; import flash.utils.ByteArray; import flash.utils.Endian; /** * Reads the bytes of a SWF (as a ByteArray) to acquire * information from the SWF file header. Some of * this information is inaccessible to ActionScript * otherwise. + * + * @author Trevor McCauley - www.senocular.com */ public class SWFReader { // properties starting with those // found first in the byte stream /** * Indicates whether or not the SWF * is compressed. */ public var compressed:Boolean; /** * The major version of the SWF. */ public var version:uint; /** * The file size of the SWF. */ public var fileSize:uint; // compression starts here if SWF compressed: /** * The dimensions of the SWF in the form of * a Rectangle instance. */ public function get dimensions():Rectangle { return _dimensions; } private var _dimensions:Rectangle = new Rectangle(); // dimensions gets accessor since we don't // want people nulling the rect; it should // always have a value, even if 0-ed /** * Width of the stage as defined by the SWF. * Same as dimensions.width. */ public function get width():uint { return uint(_dimensions.width); } /** * Height of the stage as defined by the SWF. * Same as dimensions.height. */ public function get height():uint { return uint(_dimensions.height); } /** * When true, the bytes supplied in calls made to the tagCallback * function includes the RECORDHEADER of that tag which includes * the tag and the size of the tag. By default (false) this * information is not included. */ public function get tagCallbackBytesIncludesHeader():Boolean { return _tagCallbackBytesIncludesHeader; } public function set tagCallbackBytesIncludesHeader(value:Boolean):void { _tagCallbackBytesIncludesHeader = value; } private var _tagCallbackBytesIncludesHeader:Boolean = false; /** * The frame rate of the SWF in frames * per second. */ public var frameRate:uint; /** * The total number of frames of the SWF. */ public var totalFrames:uint; /** * ActionScript version. */ public var asVersion:uint; /** * Determines local playback security; when * true, indicates that when this file is * run locally, it can only access the network. * When false, only local files can be accessed. * This does not apply when the SWF is being * run in a local-trusted sandbox. */ public var usesNetwork:Boolean; /** * The background color of the SWF. */ public var backgroundColor:uint; /** * Determines if the SWF is protected from * being imported into an authoring tool. */ public var protectedFromImport:Boolean; /** * Determines if remote debugging is enabled. */ public var debuggerEnabled:Boolean; /** * The XMP metadata defined in the SWF. */ public var metadata:XML; /** * Maximun allowed levels of recursion. */ public var recursionLimit:uint; /** * Time in seconds a script will run in a * single frame before a timeout error * occurs. */ public var scriptTimeoutLimit:uint; /** * The level of hardware acceleration specified * for the SWF. 0 is none, 1 is direct, and 2 * is GPU (Flash Player 10+). */ public var hardwareAcceleration:uint; /** * A callback function that will be called when * a tag is read during the parse process. The * callback function should contain the parameters * (tag:uint, bytes:ByteArray). */ public var tagCallback:Function; /** * Indicates that the SWF bytes last provided * were successfully parsed. If the SWF bytes * were not successfully parsed, no SWF data * will be available. */ public var parsed:Boolean; /** * The Flash Player error message that resulted * from the error that caused a parse to fail. */ public var errorText:String = ""; // keeping track of data private var bytes:ByteArray; private var currentByte:int; // used in bit reading private var bitPosition:int; // used in bit reading private var currentTag:uint; // tag flags private var bgColorFound:Boolean; // constants private const GET_DATA_SIZE:int = 5; private const TWIPS_TO_PIXELS:Number = 0.05; // 20 twips in a pixel private const TAG_HEADER_ID_BITS:int = 6; private const TAG_HEADER_MAX_SHORT:int = 0x3F; private const SWF_C:uint = 0x43; // header characters private const SWF_F:uint = 0x46; private const SWF_W:uint = 0x57; private const SWF_S:uint = 0x53; private const TAG_ID_EOF:uint = 0; // recognized SWF tags private const TAG_ID_BG_COLOR:uint = 9; private const TAG_ID_PROTECTED:uint = 24; private const TAG_ID_DEBUGGER1:uint = 58; private const TAG_ID_DEBUGGER2:uint = 64; private const TAG_ID_SCRIPT_LIMITS:uint = 65; private const TAG_ID_FILE_ATTS:uint = 69; private const TAG_ID_META:uint = 77; private const TAG_ID_SHAPE_1:uint = 2; private const TAG_ID_SHAPE_2:uint = 22; private const TAG_ID_SHAPE_3:uint = 32; private const TAG_ID_SHAPE_4:uint = 83; /** * SWFHeader constructor. * @param swfBytes Bytes of the SWF in a ByteArray. * You can get the bytes of a SWF by loading it into * a URLLoader or using Loader.bytes once a SWF has * been loaded into that Loader. */ public function SWFReader(swfBytes:ByteArray = null) { parse(swfBytes); } /** * Provides a string presentation of the SWFHeader * object which outlines the different values * obtained from a parsed SWF * @return The String form of the instance */ public function toString():String { if (parsed) { var compression:String = (compressed) ? "compressed" : "uncompressed"; var frames:String = totalFrames > 1 ? "frames" : "frame"; return "[SWF" + version + " AS" + asVersion + ".0: " + totalFrames + " " + frames + " @ " + frameRate + " fps " + _dimensions.width + "x" + _dimensions.height + " " + compression + "]"; } // default toString if SWF not parsed return Object.prototype.toString.call(this) as String; } /** * Parses the bytes of a SWF file to extract * properties from its header. * @param swfBytes Bytes of a SWF to parse. */ public function parse(swfBytes:ByteArray):void { parseDefaults(); // null bytes, exit if (swfBytes == null) { parseError("Error: Cannot parse a null value."); return; } // assume at start parse completed successfully // on failure, this will be set to false parsed = true; // -------------------------------------- // HEADER // -------------------------------------- try { // try to parse the bytes. Failures // results in cleared values for the data bytes = swfBytes; bytes.endian = Endian.LITTLE_ENDIAN; bytes.position = 0; // get header characters var swfFC:uint = bytes.readUnsignedByte(); // F, or C if compressed var swfW:uint = bytes.readUnsignedByte(); // W var swfS:uint = bytes.readUnsignedByte(); // S // validate header characters if ((swfFC != SWF_F && swfFC != SWF_C) || swfW != SWF_W || swfS != SWF_S) { parseError("Error: Invalid SWF header."); return; } compressed = Boolean(swfFC == SWF_C); // == SWF_F if not compressed version = bytes.readUnsignedByte(); fileSize = bytes.readUnsignedInt(); // mostly redundant since we should have full bytes // if compressed, need to uncompress // the data after the first 8 bytes // (first 8 already read above) if (compressed) { // use a temporary byte array to // represent the compressed portion // of the SWF file var temp:ByteArray = new ByteArray(); bytes.readBytes(temp); bytes = temp; bytes.endian = Endian.LITTLE_ENDIAN; bytes.position = 0; temp = null; // temp no longer needed bytes.uncompress(); // Note: at this point, the original // uncompressed 8 bytes are no longer // part of the current bytes byte array } _dimensions = readRect(); bytes.position++; // one up after rect frameRate = bytes.readUnsignedByte(); totalFrames = bytes.readUnsignedShort(); } catch (error:Error) { // header parse error parseError(error.message); return; } // -------------------------------------- // TAGS // -------------------------------------- // read all the tags in the file // up until the END tag try { while (readTag()) { // noop } } catch (error:Error) { // error in tag parsing. EOF would throw // an error, but the END tag should be // reached before that occurs parseError(error.message); return; } // parse completed successfully! // null bytes since no longer needed bytes = null; } /** * Defines default values for all the class * properties. This is used to have accurate * values for properties which may not be * present in the SWF file such as asVersion * which is only required to be specified in * SWF8 and above (in FileAttributes tag). */ private function parseDefaults():void { compressed = false; version = 1; // SWF1 fileSize = 0; _dimensions = new Rectangle(); frameRate = 12; // default from Flash authoring (flex == 24) totalFrames = 1; metadata = null; asVersion = ActionScriptVersion.ACTIONSCRIPT2; // 2 if not explicit usesNetwork = false; backgroundColor = 0xFFFFFF; // white background protectedFromImport = false; debuggerEnabled = true; scriptTimeoutLimit = 256; recursionLimit = 15; hardwareAcceleration = 0; errorText = ""; // clear existing error text // tag helper flags bgColorFound = false; } /** * Clears variable data and logs an error * message. */ private function parseError(message:String = "Unkown error."):void { compressed = false; version = 0; fileSize = 0; _dimensions = new Rectangle(); frameRate = 0; totalFrames = 0; metadata = null; asVersion = 0; usesNetwork = false; backgroundColor = 0; protectedFromImport = false; debuggerEnabled = false; scriptTimeoutLimit = 0; recursionLimit = 0; hardwareAcceleration = 0; parsed = false; bytes = null; errorText = message; } /** * Utility to convert a unit value into a string * in hex style padding value with "0" characters. * @return The string representation of the hex value. */ private function paddedHex(value:uint, numChars:int = 6):String { var str:String = value.toString(16); while (str.length < numChars) str = "0" + str; return "0x" + str; } /** * Reads a string in the byte stream by * reading all bytes until a null byte (0) * is reached. * @return The string having been read. */ private function readString():String { // find ending null character that // terminates the string var i:uint = bytes.position; try { while (bytes[i] != 0) i++; } catch (error:Error) { return ""; } // null byte should have been found // return the read string return bytes.readUTFBytes(i - bytes.position); } /** * Reads RECT data from the current * location in the current bytes object * @return A rectangle object whose values * match those of the RECT read. */ private function readRect():Rectangle { nextBitByte(); var rect:Rectangle = new Rectangle(); var dataSize:uint = readBits(GET_DATA_SIZE); rect.left = readBits(dataSize, true) * TWIPS_TO_PIXELS; rect.right = readBits(dataSize, true) * TWIPS_TO_PIXELS; rect.top = readBits(dataSize, true) * TWIPS_TO_PIXELS; rect.bottom = readBits(dataSize, true) * TWIPS_TO_PIXELS; return rect; } private function readMatrix():Matrix { nextBitByte(); var dataSize:uint; var matrix:Matrix = new Matrix(); if (readBits(1)) { // has scale dataSize = readBits(GET_DATA_SIZE); matrix.a = readBits(dataSize, true); matrix.d = readBits(dataSize, true); } if (readBits(1)) { // has rotation dataSize = readBits(GET_DATA_SIZE); matrix.b = readBits(dataSize, true); matrix.c = readBits(dataSize, true); } // translation dataSize = readBits(GET_DATA_SIZE); matrix.tx = readBits(dataSize, true) * TWIPS_TO_PIXELS; matrix.ty = readBits(dataSize, true) * TWIPS_TO_PIXELS; return matrix; } /** * Reads a series of bits from the current byte * defined by currentByte based on the but at * position bitPosition. If more bits are required * than are available in the current byte, the next * byte in the bytes array is read and the bits are * taken from there to complete the request. * @param numBits The number of bits to read. * @return The bits read as a uint. */ private function readBits(numBits:uint, signed:Boolean = false):Number { var value:Number = 0; // int or uint var remaining:uint = 8 - bitPosition; var mask:uint; // can get all bits from current byte if (numBits <= remaining) {
as3/as3-utils
e212da680804a87b9b8c5aff2545303d20e1029f
Added contribution guidelines
diff --git a/Contribution Guidelines.md b/Contribution Guidelines.md new file mode 100644 index 0000000..c0bef77 --- /dev/null +++ b/Contribution Guidelines.md @@ -0,0 +1,125 @@ +#Contribution Guidelines + +As developers, many of us have created our own working set of classes and functions for handling the common programming tasks we come across every day. But why reinvent the wheel? **AS3-Utils** is an attempt to gather together code from all of these disparate libraries into one place in hopes of creating a reusable, well-tested, well-documented, and freely-available unified collection. + +If you have code in a personal library / pile of snippets that you'd like to add, please refer to these guidelines. + +##What to contribute + +###Functions vs. Classes + +We've been leaning towards a *functions only* approach. This means: + +1. You can type "utils.foo.bar" to explore what's available in any IDE. + +2. You only have to import the single function you need instead of a class. + +3. Fewer dependencies on other pieces of the library. Less reading documents in order to use the functionality you want. + +If you have a utility class that you'd like to add to the library, try breaking it into smaller functions before adding it. In other words, don't add `com.you.ArrayUtil`, instead add the functions within as standalone .as files. + +_Are there cases where classes are okay? It seems like more generic classes that act as datatypes could be okay especially if their set of functions was separated out of the class. A good example might be 2d or 3d Vectors or commonly used interfaces like IDisplayObject._ + +####Constants + +Constants that can be used in a general way can be added. If there is a single constant, Pi for example, you can add it as its own standalone .as file. + + // PI.as + package utils.number { + public const PI:Number = 3.141; //etc. + } + +If the constant value is part of an enumeration of values, you may include it in an enumeration class. + + // CommonColors.as + package utils.color { + public class CommonColors { + public const R:uint = 0xFF0000; + public const G:uint = 0x00FF00; + public const B:uint = 0x0000FF; + } + } + +###Contributing Libraries + +_I'm not sure what our policy should be for adding complete code libraries or SWCs. I could see things like the [AS3 Data Structures](http://code.google.com/p/polygonal/wiki/DataStructures) or the [AS3 Core Lib](https://github.com/mikechambers/as3corelib) being useful but maybe it's better to keep them separate. We could create a text list of recommended libraries and put it in the docs?_ + +_Perhaps we could create a branch that includes other complete libraries as is so they can be updated as needed._ + +_It would be good to create a "libraries to integrate" list as well._ + +###Naming + +Please use self-explanatory names for your functions and avoid using abbreviations. Strive for clarity over brevity. + +Remember that in common practice the package name will not be included in people's code. Therefore, to make code more readable, avoid ambiguous names for functions and classes. Rather than relying on the package name to imply what the function does, include include it in the name of the function. + +Examples: + +* `truncateMultilineText()`, NOT `truncMLText()` + +* `convertHexStringToUint(hexString:String):uint`, NOT `convertToUint(s:String):uint` + +* `XMLConstants` or better yet, `XMLNodeType`, NOT `Constants` + +* `utils.foo.getFooAsString()`, NOT `utils.foo.toString()` + +###Packages + +Here are general guidelines for how to pick a package. + +* Check to see what packages already exist before creating a new one. If possible, use one of the existing packages. **Do not** use your own package names (e.g. `com.mimswright`) + +* If a utility function operates mainly on a particular class from the Flash Player API, use the same package name as that class. E.g. if your function deals mostly with `Sprites`, use the `utils.display` package. + +* If your function is related to a root-level class in the Flash API, such as `Array`, use `utils.array`. + +* If you have a significant set of functions that relates to a specific class within a package, you may create a new package just for that class. For example, if you have several functions that all deal with `Point`, could go in `utils.geom.point`. + +* If you're Peter Piper, pick a peck of pickled packages. + +##Deprecating and Replacing Existing Code + +What do you do if you want to contribute a piece of code that is very similar to one that already exists? + +* **First, always check for code that could function similarly to your code.** + +* If you find similar code to something you want to commit, think carefully. + + * If your code and their code do virtually the same thing, suck it up and **keep their code**. + + * If your code and their code have the same method signature (same arguments and return type) but yours is more robust or powerful, **update their code** with your improvements keeping the original function name and signature. + + * If your code is clearly better and more complete than their code and updating or renaming it just wouldn't cut it, **move their code** into the `deprecated` package and replace it with your code. Add a note to their code explaining why it was deprecated. You can also add [deprecated metadata tags](http://danielmclaren.net/node/135). The `deprecated` package should be cleared out for each major version release. + +* If you find code that is a duplicate of another piece of code, keep the one that is clearer and more robust and deprecate the other. + +##Unit Tests + +_Someone with more experience with testing should probably write this._ + +Needless to say, code should not cause any compile errors or warnings. + +##Merge Strategy + +Committers should follow these steps when submitting code to the project. + +1. Create a fork of the project. + +1. Make your changes, test, and commit them. + +1. When you're ready to integrate the changes into the main branch, create a pull request. + +1. Don't merge your own pull request even if you're an admin. Instead, ask for assistance from someone else to review your pull request and merge it into the master. + +1. If you are anxious with waiting for your pull request to be handled, review and pull someone else's code while you wait. + +###Why not merge your own code? + +This is a collection made for everyone made up of several people's personal code library. The chances of adding duplicate or idiosyncratic code is very high. Using the pull-request scheme is a great way for us to make sure all the code is being reviewed by *someone* other than the author. The more people who review code the less chance of checking in a duplicate or buggy piece of code. + +Furthermore, gitHub is set up to handle a distributed repository workflow very elegantly. If at any point you want to break out and work on your own personal code library, that's easy to do in your own fork. + +##Documentation + +Please add [ASDoc](http://help.adobe.com/en_US/flex/using/WSd0ded3821e0d52fe1e63e3d11c2f44bb7b-7fe7.html)-style documentation whenever your code's purpose isn't completely obvious. Feel free to add docs to other people's code if there is none. Most importantly, please add `@author` tags to your work and to others' (if you know who wrote something). \ No newline at end of file
as3/as3-utils
cf82a89b6b82899a4a1b6843d100e4e3601f2016
Added contribution guidelines
diff --git a/Contribution Guidelines.md b/Contribution Guidelines.md new file mode 100644 index 0000000..c0bef77 --- /dev/null +++ b/Contribution Guidelines.md @@ -0,0 +1,125 @@ +#Contribution Guidelines + +As developers, many of us have created our own working set of classes and functions for handling the common programming tasks we come across every day. But why reinvent the wheel? **AS3-Utils** is an attempt to gather together code from all of these disparate libraries into one place in hopes of creating a reusable, well-tested, well-documented, and freely-available unified collection. + +If you have code in a personal library / pile of snippets that you'd like to add, please refer to these guidelines. + +##What to contribute + +###Functions vs. Classes + +We've been leaning towards a *functions only* approach. This means: + +1. You can type "utils.foo.bar" to explore what's available in any IDE. + +2. You only have to import the single function you need instead of a class. + +3. Fewer dependencies on other pieces of the library. Less reading documents in order to use the functionality you want. + +If you have a utility class that you'd like to add to the library, try breaking it into smaller functions before adding it. In other words, don't add `com.you.ArrayUtil`, instead add the functions within as standalone .as files. + +_Are there cases where classes are okay? It seems like more generic classes that act as datatypes could be okay especially if their set of functions was separated out of the class. A good example might be 2d or 3d Vectors or commonly used interfaces like IDisplayObject._ + +####Constants + +Constants that can be used in a general way can be added. If there is a single constant, Pi for example, you can add it as its own standalone .as file. + + // PI.as + package utils.number { + public const PI:Number = 3.141; //etc. + } + +If the constant value is part of an enumeration of values, you may include it in an enumeration class. + + // CommonColors.as + package utils.color { + public class CommonColors { + public const R:uint = 0xFF0000; + public const G:uint = 0x00FF00; + public const B:uint = 0x0000FF; + } + } + +###Contributing Libraries + +_I'm not sure what our policy should be for adding complete code libraries or SWCs. I could see things like the [AS3 Data Structures](http://code.google.com/p/polygonal/wiki/DataStructures) or the [AS3 Core Lib](https://github.com/mikechambers/as3corelib) being useful but maybe it's better to keep them separate. We could create a text list of recommended libraries and put it in the docs?_ + +_Perhaps we could create a branch that includes other complete libraries as is so they can be updated as needed._ + +_It would be good to create a "libraries to integrate" list as well._ + +###Naming + +Please use self-explanatory names for your functions and avoid using abbreviations. Strive for clarity over brevity. + +Remember that in common practice the package name will not be included in people's code. Therefore, to make code more readable, avoid ambiguous names for functions and classes. Rather than relying on the package name to imply what the function does, include include it in the name of the function. + +Examples: + +* `truncateMultilineText()`, NOT `truncMLText()` + +* `convertHexStringToUint(hexString:String):uint`, NOT `convertToUint(s:String):uint` + +* `XMLConstants` or better yet, `XMLNodeType`, NOT `Constants` + +* `utils.foo.getFooAsString()`, NOT `utils.foo.toString()` + +###Packages + +Here are general guidelines for how to pick a package. + +* Check to see what packages already exist before creating a new one. If possible, use one of the existing packages. **Do not** use your own package names (e.g. `com.mimswright`) + +* If a utility function operates mainly on a particular class from the Flash Player API, use the same package name as that class. E.g. if your function deals mostly with `Sprites`, use the `utils.display` package. + +* If your function is related to a root-level class in the Flash API, such as `Array`, use `utils.array`. + +* If you have a significant set of functions that relates to a specific class within a package, you may create a new package just for that class. For example, if you have several functions that all deal with `Point`, could go in `utils.geom.point`. + +* If you're Peter Piper, pick a peck of pickled packages. + +##Deprecating and Replacing Existing Code + +What do you do if you want to contribute a piece of code that is very similar to one that already exists? + +* **First, always check for code that could function similarly to your code.** + +* If you find similar code to something you want to commit, think carefully. + + * If your code and their code do virtually the same thing, suck it up and **keep their code**. + + * If your code and their code have the same method signature (same arguments and return type) but yours is more robust or powerful, **update their code** with your improvements keeping the original function name and signature. + + * If your code is clearly better and more complete than their code and updating or renaming it just wouldn't cut it, **move their code** into the `deprecated` package and replace it with your code. Add a note to their code explaining why it was deprecated. You can also add [deprecated metadata tags](http://danielmclaren.net/node/135). The `deprecated` package should be cleared out for each major version release. + +* If you find code that is a duplicate of another piece of code, keep the one that is clearer and more robust and deprecate the other. + +##Unit Tests + +_Someone with more experience with testing should probably write this._ + +Needless to say, code should not cause any compile errors or warnings. + +##Merge Strategy + +Committers should follow these steps when submitting code to the project. + +1. Create a fork of the project. + +1. Make your changes, test, and commit them. + +1. When you're ready to integrate the changes into the main branch, create a pull request. + +1. Don't merge your own pull request even if you're an admin. Instead, ask for assistance from someone else to review your pull request and merge it into the master. + +1. If you are anxious with waiting for your pull request to be handled, review and pull someone else's code while you wait. + +###Why not merge your own code? + +This is a collection made for everyone made up of several people's personal code library. The chances of adding duplicate or idiosyncratic code is very high. Using the pull-request scheme is a great way for us to make sure all the code is being reviewed by *someone* other than the author. The more people who review code the less chance of checking in a duplicate or buggy piece of code. + +Furthermore, gitHub is set up to handle a distributed repository workflow very elegantly. If at any point you want to break out and work on your own personal code library, that's easy to do in your own fork. + +##Documentation + +Please add [ASDoc](http://help.adobe.com/en_US/flex/using/WSd0ded3821e0d52fe1e63e3d11c2f44bb7b-7fe7.html)-style documentation whenever your code's purpose isn't completely obvious. Feel free to add docs to other people's code if there is none. Most importantly, please add `@author` tags to your work and to others' (if you know who wrote something). \ No newline at end of file
as3/as3-utils
2546ccf203ec71da35014b5b5669ff3424c21564
Added deprected folder
diff --git a/src/deprecated/.gitignore b/src/deprecated/.gitignore new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/src/deprecated/.gitignore @@ -0,0 +1 @@ +
as3/as3-utils
5a9261496a52e028ad6aed6ee6da2887ea003950
styleFields fix.
diff --git a/src/utils/textField/styleFields.as b/src/utils/textField/styleFields.as index 50cb6b5..51d4973 100644 --- a/src/utils/textField/styleFields.as +++ b/src/utils/textField/styleFields.as @@ -1,34 +1,38 @@ package utils.textField { import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; import flash.text.StyleSheet; import flash.text.TextField; /** - * Apply the application stylesheet to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObject</code>. + * Apply the application stylesheet to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObjectContainer</code>. * * <p><b>Warning</b>: Unlike <code>formatFields</code> you must <i>reset</i> your <code>htmlText</code> to have the style applied.</p> * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. * @param stylesheet to apply to the <code>TextField</code>'s (Default: <code>App.css</code>). * @see sekati.core.App#css */ public function styleFields(o:DisplayObject, stylesheet:StyleSheet):void { + var tf:TextField; var css:StyleSheet = stylesheet; if (o is TextField) { - var tf:TextField = o as TextField; + tf = o as TextField; tf.styleSheet = css; } - else if (o is DisplayObject) + else if (o is DisplayObjectContainer) { - for (var i:String in o) + var container:DisplayObjectContainer = o as DisplayObjectContainer; + for (var i:int = 0; i < container.numChildren; i++) { - if (o[i] is TextField && !o[i].styleSheet) + if (container.getChildAt(i) is TextField) { - o[i].styleSheet = css; + tf = container.getChildAt(i) as TextField; + tf.styleSheet = css; } } } } } \ No newline at end of file
as3/as3-utils
fe357ca444154ddf8b60f534e2965dd64a2f5779
formatFields fix.
diff --git a/src/utils/textField/formatFields.as b/src/utils/textField/formatFields.as index 635a5e1..ba2e8c1 100644 --- a/src/utils/textField/formatFields.as +++ b/src/utils/textField/formatFields.as @@ -1,30 +1,34 @@ package utils.textField { import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; import flash.text.TextField; import flash.text.TextFormat; /** - * Apply a <code>TextFormat</code> to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObject</code>. + * Apply a <code>TextFormat</code> to a <code>TextField</code> or to all <code>TextField</code>'s in a <code>DisplayObjectContainer</code>. * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. * @param textFormat to apply to the <code>TextField</code>'s. */ public function formatFields(o:DisplayObject, textFormat:TextFormat):void { + var tf:TextField; if (o is TextField) { - var tf:TextField = o as TextField; + tf = o as TextField; tf.setTextFormat(textFormat); } - else if (o is DisplayObject) + else if (o is DisplayObjectContainer) { - for (var i:String in o) + var container:DisplayObjectContainer = o as DisplayObjectContainer; + for (var i:int = 0; i < container.numChildren; i++) { - if (o[i] is TextField && !o[i].styleSheet) + if (container.getChildAt(i) is TextField) { - o[i].setTextFormat(textFormat); + tf = container.getChildAt(i) as TextField; + tf.setTextFormat(textFormat); } } } } } \ No newline at end of file
as3/as3-utils
30f8cc1078008a301196f82784997ccfdb8140bd
clearFields fix.
diff --git a/src/utils/textField/clearFields.as b/src/utils/textField/clearFields.as index dfac4ef..276b078 100644 --- a/src/utils/textField/clearFields.as +++ b/src/utils/textField/clearFields.as @@ -1,28 +1,32 @@ package utils.textField { import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; import flash.text.TextField; /** - * Clear a <code>TextField</code> text or to all <code>TextField</code>'s texts in a <code>DisplayObject</code>. + * Clear a <code>TextField</code> text or to all <code>TextField</code>'s texts in a <code>DisplayObjectContainer</code>. * @param o <code>DisplayObject</code> that either <i>is</i> or contains <code>TextField</code>'s. */ public function clearFields(o:DisplayObject):void { + var tf:TextField; if (o is TextField) { - var tf:TextField = o as TextField; + tf = o as TextField; tf.text = tf.htmlText = ''; } - else if (o is DisplayObject) + else if (o is DisplayObjectContainer) { - for (var i:String in o) + var container:DisplayObjectContainer = o as DisplayObjectContainer; + for (var i:int = 0; i < container.numChildren; i++) { - if (o[i] is TextField) + if (container.getChildAt(i) is TextField) { - o[i].text = o[i].htmlText = ''; + tf = container.getChildAt(i) as TextField; + tf.text = tf.htmlText = ''; } } } } } \ No newline at end of file