Compare commits

...
153 Commits
Author SHA1 Message Date
Ross Boucher 6678bba94f Add manual memory management to Cappuccino. 2010-03-31 19:36:47 -07:00
Ross Boucher acac29dcda Merge branch 'master' of github.com:280north/cappuccino 2010-03-31 16:37:16 -07:00
Paul BaumgartandTom Robinson 675969af6d Add some dependency checking to bootstrap.sh: make sure correct JVM is
being used and ensure other dependencies are installed and on the $PATH.
2010-03-31 15:00:09 -07:00
Tom Robinson ce32177e1d Use "CommonJS" task as the dependency for "test" task for now. 2010-03-31 13:53:09 -07:00
Randall Luecke e956d61a08 Fixed bug introduced by renaming of private class. 2010-03-31 16:41:13 -04:00
Alexander LjungbergandRoss Boucher 068cdb9817 CPNull valueForKey:X returns CPNull for any value of X, paralleling [nil valueForKey:X]. Verified against Cocoa through empirical testing. 2010-03-31 13:17:42 -07:00
Randall Luecke 0ec7d4cd9a Made drag feedback view in the tableview more correct, fixed encoding issues.
Conflicts:

	AppKit/CPTableView.j
2010-03-31 16:11:10 -04:00
Nicholas Small 6a8126337c Added right click responder methods and context menu support. 2010-03-31 15:56:18 -04:00
Ross Boucher 12db25a829 Fix for a potential error in IE when setting a width to a negative value. 2010-03-31 12:11:21 -07:00
Ross Boucher a347bfb8b1 Sprite images recursively. 2010-03-31 11:10:17 -07:00
Francisco Ryan Tolmasky I 9255af210c Fix for loading Cappuccino apps locally on Windows.
Reviewed by me.
2010-03-30 16:28:42 -07:00
Tom Robinson 0b3264a99d Enable default logger in debug frameworks. Add configurable options to index-debug.html. 2010-03-30 14:12:59 -07:00
Ross Boucher 2bf16da441 These menu key equivs were incorrect. 2010-03-30 11:10:36 -07:00
Ross Boucher 5c4d890100 Fix a nil variable error that caused problems in Firefox 2. 2010-03-30 10:52:48 -07:00
Francisco Ryan Tolmasky I 99282026fa One more fix for image spriting.
Reviewed by me.
2010-03-30 00:45:11 -07:00
Francisco Ryan Tolmasky I 8f4b2a7cfd Fail more gracefully when main cib is not found.
Reviewed by me.
2010-03-29 23:20:31 -07:00
Randall Luecke c78feda3d6 Fixed nib2cib bug with cornerview where resources were not loaded from the correct location. 2010-03-30 01:45:36 -04:00
Francisco Ryan Tolmasky I a279d62c88 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-28 11:40:38 -07:00
Francisco Ryan Tolmasky I 8d1f787179 Fix for a few minor regressions:
1. Split out flatten specific code to get file size back down.
2. Fix for non-native string URL not working with the URLCache (typeof x !=== "string")
3. Fix for slight IE performance regression.

Reviewed by me.
2010-03-28 11:39:36 -07:00
Ross Boucher 7ab41cf195 If there is no key window or no main window make the first opened window those things. 2010-03-28 09:03:33 -07:00
Ross Boucher df728b7a21 Support terminating method signatures with ;. Closes #416. 2010-03-28 08:51:35 -07:00
Francisco Ryan Tolmasky I cba26faf9b Fix for HelloWorld not flattening correctly.
Reviewed by me.
2010-03-27 19:31:16 -07:00
Francisco Ryan Tolmasky I c4c1cffc01 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-27 18:53:03 -07:00
Francisco Ryan Tolmasky I 321706e5c6 Fix for user code errors during load not being reported (Cappuccino failing silently).
Reviewed by me.
2010-03-27 18:52:19 -07:00
Ross Boucher 47bf4c0baa Finish split view cursor implementation.
Closes #494.
2010-03-27 15:47:10 -07:00
Alexander LjungbergandRoss Boucher fc628c1221 CPSplitView resize cursors now require [[self window] setAcceptsMouseMovedEvents:YES]; to be called manually pending a CPTrackingArea based implementation. 2010-03-27 15:47:10 -07:00
Ross Boucher eb6a03704a Proper resize cursors for CPSplitView. Also enables resize cursor for additionalEffectiveRectOfDividerAtIndex areas.
Conflicts:

	AppKit/CPSplitView.j
2010-03-27 15:47:10 -07:00
Francisco Ryan Tolmasky I 7b855e6c68 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-27 13:56:35 -07:00
Francisco Ryan Tolmasky I fe0818c612 Don't generate image files if there aren't any.
Reviewed by me.
2010-03-27 13:54:07 -07:00
Ross Boucher 74dabcae8a Update the CPDictionary test suite. 2010-03-27 13:52:44 -07:00
Emmanuel MaillardandRoss Boucher daf7870bab - add containsKey: method 2010-03-27 13:41:32 -07:00
Ross Boucher 64da7f8775 define out DOM code from _CPImageAndTextView.
Closes #562.
2010-03-27 13:37:13 -07:00
aburkhalterandRoss Boucher 6cfa11a94d Initial boilerplate and file for putting the untested (at least not directly) CPView.j under test. Initial test to confirm we can actually create the object and a test demonstrating issue #562. 2010-03-27 13:33:04 -07:00
Ross Boucher db3c6c1463 A few minor updates to the pathExtension patch. 2010-03-27 13:25:44 -07:00
Emmanuel MaillardandRoss Boucher 65a669a9a1 - correct pathExtension and stringByDeletingPathExtension 2010-03-27 13:23:55 -07:00
Emmanuel MaillardandRoss Boucher 33f56bb203 - implement stringByDeletingPathExtension 2010-03-27 13:23:32 -07:00
Emmanuel MaillardandRoss Boucher 1ff873e170 - add tests for pathExtension and stringByDeletingPathExtension 2010-03-27 13:22:36 -07:00
Ross Boucher b0e0156880 Fix support for initial first responder. 2010-03-27 13:08:47 -07:00
Ross Boucher 896f36dffb A better (but not perfect) way to handle the browser's first responder state. 2010-03-27 11:27:44 -07:00
Ross Boucher eae975652e Add default line break mode. 2010-03-26 16:59:02 -07:00
Ross Boucher e46d1a793c autoresize the cpbrowser test browser. 2010-03-26 16:41:33 -07:00
Ross Boucher 1c9763eaa8 CPBox should autoresize its content view. 2010-03-26 16:41:23 -07:00
Ross Boucher 686370ac0e Add convenience accessors for the browser's selected items. 2010-03-26 15:52:53 -07:00
Ross Boucher e4ca057e4c Fix import directives. 2010-03-26 14:27:46 -07:00
Ross Boucher ac5a0e3dfc Add CPBrowser manual test app. 2010-03-26 14:00:51 -07:00
Ross Boucher a580b522e3 Add initial CPBrowser implementation. 2010-03-26 14:00:30 -07:00
Ross Boucher af53c271c7 Fix a few naming convention violations.
Make dragView.... use the columns its passed, rather than computing from scratch.
2010-03-26 13:59:41 -07:00
Ross Boucher 4476dad395 Whitespace fix. 2010-03-26 10:36:08 -07:00
Emmanuel MaillardandRoss Boucher b7b2dd2915 - CGPathAddQuadCurveToPoint fix for an unknown variable when using a transformation matrix 2010-03-26 10:36:08 -07:00
Francisco Ryan Tolmasky I efb6a0f5c6 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-26 01:31:39 -07:00
Francisco Ryan Tolmasky I deba653661 Fix for unrecognized selector in CPURL's initWithCoder:.
Reviewed by me.
2010-03-26 01:30:50 -07:00
Ross Boucher eb831dc4ac Typo. Closes #572. 2010-03-25 10:40:37 -07:00
Scott KyleandRoss Boucher b0d355a71c Some somewhat minor style fixes 2010-03-24 19:46:38 -07:00
Ross Boucher af11b4e423 Fix for pattern images not being displayed correctly under the new background color system 2010-03-23 14:32:24 -07:00
Ross Boucher 0cf86318ce Make semi-transparent background colors work in browsers that don't support RGBA.
Closes #569.
2010-03-23 14:26:32 -07:00
Ross Boucher 4175b762c3 Disable new syntax check while we work out the build issue some people are having. 2010-03-23 13:29:55 -07:00
Ross Boucher 3ddcb5f118 Remove duplicate method declaration. 2010-03-23 13:29:43 -07:00
Ross Boucher d0ad865976 Add the with{} back in for Class methods, instead take the disallowed list from objj_class. 2010-03-23 11:21:59 -07:00
Ross Boucher 7013b34897 Add a few additional syntax checks.
Throw an error if a method uses a parameter name that is also an ivar name.
Stop using with{} block for class methods.
2010-03-23 11:21:59 -07:00
Ross Boucher bbbae36e6a Missing - on a method. 2010-03-23 11:21:59 -07:00
Francisco Ryan Tolmasky I 34c3a9530b Fixed a bug where CPKeyedUnarchiver would incorrectly unarchive 0 as null.
Reviewed by me.
2010-03-23 02:06:44 -07:00
Francisco Ryan Tolmasky I 78cb522874 Temporarily revert "Make semi-transparent background colors work in browsers that don't support RGBA."
This fix was making lots of resources not show up.

This reverts commit f8c13f1e30.
2010-03-23 01:22:59 -07:00
Francisco Ryan Tolmasky I e8a0d2acf6 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-23 00:04:59 -07:00
Ross Boucher f8c13f1e30 Make semi-transparent background colors work in browsers that don't support RGBA.
Closes #569.
2010-03-22 19:00:49 -07:00
Randall Luecke 4b272a76fd Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-22 19:27:13 -04:00
Randall Luecke f73d96af08 Fixed black background of dragview in Opera and IE. 2010-03-22 19:24:32 -04:00
Scott KyleandRoss Boucher bb0835e2f3 CPImageView should send action on drop, as in Cocoa 2010-03-22 16:15:02 -07:00
Ross Boucher ef4c108b9e Date test wasn't accurately accounting for daylight savings time. 2010-03-22 15:08:29 -07:00
Ross Boucher 319b9ed00f Use === not ==. 2010-03-22 14:53:49 -07:00
Alan RogersandRoss Boucher 35b62ca53f Updated test and fix for gh issue #539 2010-03-22 14:53:07 -07:00
Alan RogersandRoss Boucher 4e1e6f3c0b Little fix for CPDictionary, we should not try and recursively convert null JSON objects. 2010-03-22 14:52:55 -07:00
Alan RogersandRoss Boucher c8f3445fa6 Adding a unit test to verify fix to +[CPDictionary dictionaryWithJSObject:(JSObject)object recursively:(BOOL)recursively] 2010-03-22 14:52:49 -07:00
Emmanuel MaillardandRoss Boucher 7aa1ae6bd4 - fix typo 2010-03-22 14:43:53 -07:00
Emmanuel MaillardandRoss Boucher 58179939bb - fix a typo in documentation 2010-03-22 14:43:31 -07:00
Scott KyleandRoss Boucher 5d3eae9022 deleteBackwards: => deleteBackward: 2010-03-22 14:30:48 -07:00
aburkhalterandRoss Boucher 05f8a10b3d Trivial syntax fixes. 2010-03-22 14:29:27 -07:00
Francisco Ryan Tolmasky I 6843df410a Fix for empty data URLs, MHTML, etc. files being created when no image resources exist, causing a useless xhr.
Reviewed by me.
2010-03-21 14:30:31 -07:00
Randall Luecke f324577014 Fixed default height in tableheader for Nib2Cib. 2010-03-21 02:54:14 -04:00
Tom Robinson df8357e1fc Add --split option to flatten. Asynchronously load multiple flattened files. 2010-03-20 23:38:40 -07:00
Tom Robinson 35d14939c4 Fix for flatten in Firefox (silly security restriction makes onreadystatechange not readable) 2010-03-20 22:32:11 -07:00
Francisco Ryan Tolmasky I f2c19ad403 Slight fix for collectionView:canDragItemsAtIndexes:withEvent: not passing the correct event.
Reviewed by me.
2010-03-20 20:58:08 -07:00
Francisco Ryan Tolmasky I ed9fee3038 Added collectionView:canDragItemAtIndexes:forEvent:.
Reviewed by me.
2010-03-20 20:56:37 -07:00
Francisco Ryan Tolmasky I 58e31b9cb4 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-19 12:25:39 -07:00
Francisco Ryan Tolmasky I 401ee3fd94 Added itemAtIndex: to CPCollectionView and updates API names.
Reviewed by me.
2010-03-19 12:24:07 -07:00
Randall Luecke 43b601af9b Fixed TableTest for IE. 2010-03-17 21:07:47 -04:00
Francisco Ryan Tolmasky I 5581dd71fa Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-17 01:17:50 -07:00
Tom Robinson d8fb849691 Refactor objj_eval to work in the browser. Move from CommonJS-specific code to Objective-J proper. 2010-03-16 23:57:37 -07:00
Tom Robinson 5f4281b851 Add default theme to flattened app, "-P" option for specifying other inlined files. 2010-03-16 22:38:30 -07:00
Tom Robinson 24ab176236 Make asyncLoader a configurable option on exports. 2010-03-16 22:38:30 -07:00
Tom Robinson 9c342ca19c Fix objj_eval (used in objj REPL, etc). 2010-03-16 22:38:30 -07:00
Randall Luecke 3ee3acc948 Fixed failed TableCibTest in Firefox. 2010-03-17 00:11:36 -04:00
Randall Luecke 9bdc5fa0fe Various nib2cib improvements on the tableview. 2010-03-16 22:49:38 -04:00
Randall Luecke d7a7d8e2ae Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-16 22:47:40 -04:00
Ross Boucher 5a9682b1bd Remove two calls to a dead function. 2010-03-16 18:13:57 -07:00
Randall Luecke 3c97903ed0 Fixed Nib2Cib selection color for the tableview. 2010-03-16 19:34:04 -04:00
Ross Boucher c9cf21be80 Fix for sizeWithFont: in Internet Explorer. 2010-03-16 16:01:44 -07:00
Tom Robinson f0818d94e9 Typo in window.clearNativeInterval. 2010-03-16 15:44:45 -07:00
Francisco Ryan Tolmasky I 831555cf5a Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-15 02:33:36 -07:00
Randall Luecke e0483e316e Fixed bug with nib2cib tableviews loading incorrect resources. 2010-03-14 17:24:36 -04:00
Ross Boucher c1fe45cbcd Add a way to tell a CPSplitView about a button bar for a specific divider index,
which mitigates the need to use additional effective rect delegate method when
using a split view + button bar.
2010-03-14 12:32:52 -07:00
Ross Boucher ef7ad8ee8e A few minor bug fixes for key/main window handling. 2010-03-13 22:49:06 -08:00
Ross Boucher 0ed7d46926 Add encoding support for CPButtonBar. 2010-03-13 22:49:06 -08:00
Tom Robinson ac69879fba Update flatten to use new file/function caching system. 2010-03-13 21:42:51 -08:00
Tom Robinson 50e779ef5a Add CFHTTPRequest and FileExecutable hooks for inlining files and module functions (for flatten). Removed hook used by flatten. 2010-03-13 21:35:15 -08:00
Tom Robinson 0032af1468 Merge branch 'master' of github.com:280north/cappuccino 2010-03-13 19:05:10 -08:00
Ross Boucher cf1c369dc3 Rewrite of CPButtonBar. Now it will automatically layout the buttons, and the position
and visibility of the resize control is configurable.

Also has class methods for plusButton and minusButton. API subject to change.
2010-03-13 17:37:28 -08:00
Tom Robinson ece7996895 Cleanup flatten, use resourceAtURL instead of manually walking path. 2010-03-13 01:17:47 -08:00
Randall Luecke 3cdfc1192a Fixes flickering issues with CPTableView if you hold the command key and drag. Closes #544 2010-03-13 00:07:00 -05:00
Ross Boucher 8b8998a2b9 Don't encode the search/cancel buttons. They add bloat and complicate the process. 2010-03-12 19:46:05 -08:00
Tom Robinson 677cf9e1df Change FileRequest to always use CFHTTPRequest and make async/sync configurable. Preparation for "flatten" changes. 2010-03-12 19:40:27 -08:00
Ross Boucher a08d4c6a06 Whitespace error. 2010-03-12 18:55:44 -08:00
aburkhalterandRoss Boucher e1e344dad1 Missing semi-colon. 2010-03-12 18:54:05 -08:00
aburkhalterandRoss Boucher b9427f84ae Fixes testShiftIndexesStartingAtIndex. Upward shifting no longer throws. 2010-03-12 18:53:58 -08:00
Andrew BurkhalterandRoss Boucher dc9d79bc3d Adding failing test demonstrating that CPIndexSet throws with negative delta (e.g. shifting indexes at starting point upwards). Simple downward shift example included and working successfully.
Misc method reorganization with test suite so it's a bit more intuitive.
2010-03-12 18:50:35 -08:00
Ross Boucher 503ce5502e Fix nib2cib support for CPSearchField 2010-03-12 18:49:37 -08:00
Tom Robinson 0e4d476d76 Add guard div to protect against iframes consuming events during tracking. 2010-03-12 17:25:19 -08:00
Francisco Ryan Tolmasky I cc2d579bc9 Merge branch '0.8.0' of git@github.com:280north/cappuccino 2010-03-12 03:33:21 -08:00
Tom Robinson 94bf2a36cf Updated flatten to work with new loader changes. 2010-03-11 15:56:58 -08:00
Tom Robinson 63127bf9c3 Fix CFBundle path deprecation warning and absoluteString not found. 2010-03-11 14:35:06 -08:00
Ross Boucher 033765e866 temporary fix for whiteSpace style issue in IE. 2010-03-11 14:28:31 -08:00
Ross Boucher 1634e4562a Update the template files to more modern standards. 2010-03-11 14:28:22 -08:00
Ross Boucher ed66d78585 Update the template files to more modern standards. 2010-03-11 14:27:15 -08:00
Ross Boucher 39e1514620 temporary fix for whiteSpace style issue in IE. 2010-03-11 14:18:24 -08:00
Randall Luecke 10b7eb83f1 Fixed previous commit so it doesn't break buttons in the tableview. 2010-03-09 23:52:08 -05:00
Randall Luecke 672be3991d Merge branch '0.8.0' of git://github.com/280north/cappuccino into 0.8.0 2010-03-09 23:49:03 -05:00
Randall Luecke b350c2be91 Fixed previous commit so it doesn't break buttons in the tableview. 2010-03-09 19:19:25 -05:00
Tom Robinson 68ab5bd4e7 Typo in CI script. 2010-03-09 16:12:13 -08:00
Tom Robinson bd21153300 Typo in CI script. 2010-03-09 16:07:39 -08:00
Tom Robinson 9cca7ead17 Factor out nightly build portion of CI script so not all branches push builds 2010-03-09 15:35:53 -08:00
Tom Robinson 4b1bf1fe65 Factor out nightly build portion of CI script so not all branches push builds 2010-03-09 15:32:13 -08:00
Randall Luecke 6d353f378d Fixed bug where editable tableview would not honor setEditable:NO for columns unless resized. closes #426 2010-03-09 14:43:12 -05:00
Randall Luecke cc2bb8f496 Fixed bug where editable tableview would not honor setEditable:NO for columns unless resized. closes #426 2010-03-09 14:39:26 -05:00
cacaodevandRandall Luecke 20853e3ad7 CPTableView & al. : change CPThemeStateHighlighted to CPThemeStateSelected to avoid conflicts with CPControl -highlight: method. 2010-03-09 11:43:37 -05:00
appdenandRandall Luecke 67def34e29 Added semi-colons to global vars and removed accidental gloabl variable. 2010-03-09 03:22:02 -05:00
appdenandRandall Luecke 54549b61e1 Added semi-colons to global vars and removed accidental gloabl variable. 2010-03-09 03:20:00 -05:00
Tom Robinson 3e7c3e952b Merge branch '0.8.0' of github.com:280north/cappuccino into 0.8.0 2010-03-08 19:03:14 -08:00
Francisco Ryan Tolmasky I e6411d7d90 Fix for classes declared in subfolders reporting wrong bundle (fictional).
Reviewed by me.
2010-03-08 18:27:43 -08:00
Francisco Ryan Tolmasky I 9e7d0d3183 Merge branch 'master' of git@github.com:280north/cappuccino 2010-03-08 18:23:36 -08:00
Francisco Ryan Tolmasky I 3ae4b1cf19 Fix for classes declared in subfolders reporting wrong bundle (fictional).
Reviewed by me.
2010-03-08 18:22:53 -08:00
Ross Boucher 2841223c9d Create the args and namedArgs objects in Bootstrap.js, pass them along up to CPApplication. 2010-03-08 15:14:09 -08:00
Tom Robinson ba713b8b06 Use getCappuccinoVersion() in various Jakefiles instead of hardcoded versions. 2010-03-08 15:10:08 -08:00
Tom Robinson c53bff288a Add a central version.json file. Change package building to insert version, revision, and timestamp. Auto-push tags. 2010-03-08 15:10:08 -08:00
Ross Boucher d85e8798c2 Create the args and namedArgs objects in Bootstrap.js, pass them along up to CPApplication. 2010-03-08 15:00:52 -08:00
Randall Luecke 6dbb4eedb7 Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-08 10:56:56 -05:00
Francisco Ryan Tolmasky I 33b4b94426 Fix for loading bundles generating multiple did load callbacks.
Reviewed by me.
2010-03-08 01:03:52 -08:00
Francisco Ryan Tolmasky I 3fc99095e2 Fix bug in keyed unarchiving.
Reviewed by me.
2010-03-07 23:48:23 -08:00
Randall Luecke 8410198c37 Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-08 00:58:28 -05:00
Francisco Ryan Tolmasky I d1b325052d Fixed incorrect import.
Reviewed by me.
2010-03-07 21:56:29 -08:00
Randall Luecke 4c4b42833a Added -selectedColumn to the tableview. 2010-03-08 00:00:28 -05:00
Randall Luecke 519a9300e2 Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-07 23:39:41 -05:00
Randall Luecke 7522751fd2 Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-07 20:50:29 -05:00
Randall Luecke f2165af48f Merge branch 'master' of git://github.com/280north/cappuccino 2010-03-07 10:30:17 -05:00
Randall Luecke e3a65a1847 Added preparatory support for group items in CPOutlineView. 2010-03-06 18:46:49 -05:00
152 changed files with 3731 additions and 1157 deletions
+1
View File
@@ -26,6 +26,7 @@
@import "CPApplication.j"
@import "CPBezierPath.j"
@import "CPBox.j"
@import "CPBrowser.j"
@import "CPButton.j"
@import "CPButtonBar.j"
@import "CPCheckBox.j"
+30 -44
View File
@@ -146,14 +146,14 @@ CPRunContinuesResponse = -1002;
[_mainMenu setAutoenablesItems:NO];
var bundle = [CPBundle bundleForClass:[CPApplication class]],
newMenuItem = [[CPMenuItem alloc] initWithTitle:@"New" action:@selector(newDocument:) keyEquivalent:@"N"];
newMenuItem = [[CPMenuItem alloc] initWithTitle:@"New" action:@selector(newDocument:) keyEquivalent:@"n"];
[newMenuItem setImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/New.png"] size:CGSizeMake(16.0, 16.0)]];
[newMenuItem setAlternateImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/NewHighlighted.png"] size:CGSizeMake(16.0, 16.0)]];
[_mainMenu addItem:newMenuItem];
var openMenuItem = [[CPMenuItem alloc] initWithTitle:@"Open" action:@selector(openDocument:) keyEquivalent:@"O"];
var openMenuItem = [[CPMenuItem alloc] initWithTitle:@"Open" action:@selector(openDocument:) keyEquivalent:@"o"];
[openMenuItem setImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/Open.png"] size:CGSizeMake(16.0, 16.0)]];
[openMenuItem setAlternateImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/OpenHighlighted.png"] size:CGSizeMake(16.0, 16.0)]];
@@ -166,7 +166,7 @@ CPRunContinuesResponse = -1002;
[saveMenuItem setImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/Save.png"] size:CGSizeMake(16.0, 16.0)]];
[saveMenuItem setAlternateImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/SaveHighlighted.png"] size:CGSizeMake(16.0, 16.0)]];
[saveMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Save" action:@selector(saveDocument:) keyEquivalent:@"S"]];
[saveMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Save" action:@selector(saveDocument:) keyEquivalent:@"s"]];
[saveMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Save As" action:@selector(saveDocumentAs:) keyEquivalent:nil]];
[saveMenuItem setSubmenu:saveMenu];
@@ -185,9 +185,9 @@ CPRunContinuesResponse = -1002;
[editMenu addItem:undoMenuItem];
[editMenu addItem:redoMenuItem];
[editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Cut" action:@selector(cut:) keyEquivalent:@"X"]],
[editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Copy" action:@selector(copy:) keyEquivalent:@"C"]],
[editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Paste" action:@selector(paste:) keyEquivalent:@"V"]];
[editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Cut" action:@selector(cut:) keyEquivalent:@"x"]],
[editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Copy" action:@selector(copy:) keyEquivalent:@"c"]],
[editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Paste" action:@selector(paste:) keyEquivalent:@"v"]];
[editMenuItem setSubmenu:editMenu];
[editMenuItem setHidden:YES];
@@ -860,12 +860,11 @@ CPRunContinuesResponse = -1002;
if ([windowController respondsToSelector:anAction])
return windowController;
var theDocument = [windowController document];
if (theDocument != delegate && [theDocument respondsToSelector:anAction])
if (theDocument !== delegate && [theDocument respondsToSelector:anAction])
return theDocument;
return nil;
}
@@ -874,7 +873,7 @@ CPRunContinuesResponse = -1002;
Checks for a target in the following order:
<ol>
<li>a responder from the key window</li>
<li>a responder frmo the main window</li>
<li>a responder from the main window</li>
<li>the CPApplication instance</li>
<li>the application delegate</li>
<li>the document controller</li>
@@ -913,8 +912,6 @@ CPRunContinuesResponse = -1002;
- (void)setCallback:(Function)aCallback forNextEventMatchingMask:(unsigned int)aMask untilDate:(CPDate)anExpiration inMode:(CPString)aMode dequeue:(BOOL)shouldDequeue
{
_eventListeners.push(_CPEventListenerMake(aMask, aCallback));
if (_eventListeners.length == 3) objj_debug_print_backtrace();
}
- (CPEvent)setTarget:(id)aTarget selector:(SEL)aSelector forNextEventMatchingMask:(unsigned int)aMask untilDate:(CPDate)anExpiration inMode:(CPString)aMode dequeue:(BOOL)shouldDequeue
@@ -973,10 +970,9 @@ CPRunContinuesResponse = -1002;
[self endSheet:sheet returnCode:0];
}
- (CPArray)arguments
{
if(_fullArgsString != window.location.hash)
if(_fullArgsString !== window.location.hash)
[self _reloadArguments];
return _args;
@@ -1009,12 +1005,18 @@ CPRunContinuesResponse = -1002;
- (void)_reloadArguments
{
_fullArgsString = window.location.hash;
var args = _fullArgsString.replace("#", "").split("/").slice(0);
for(var i=0, count = args.length; i<count; i++)
args[i] = decodeURIComponent(args[i]);
_args = args;
if (_fullArgsString.length)
{
var args = _fullArgsString.substring(1).split("/");
for (var i = 0, count = args.length; i < count; i++)
args[i] = decodeURIComponent(args[i]);
_args = args;
}
else
_args = [];
}
- (CPDictionary)namedArguments
@@ -1058,7 +1060,7 @@ CPRunContinuesResponse = -1002;
else if ([self mainWindow])
[[self mainWindow] makeKeyAndOrderFront:self];
else
[[[self mainMenu] window] makeKeyWindow]; //FIXME this may not actually work
[[self mainMenu]._menuWindow makeKeyWindow]; //FIXME this may not actually work
_previousKeyWindow = nil;
_previousMainWindow = nil;
@@ -1143,29 +1145,8 @@ function CPApplicationMain(args, namedArgs)
[principalClass sharedApplication];
//FIXME?
if (!args)
{
var args = [CPApp arguments];
if([args containsObject:"debug"])
CPLogRegister(CPLogPopup);
}
if (!namedArgs)
{
var searchParams = window.location.search.substring(1).split("&");
namedArgs = [CPDictionary dictionary];
for(var i=0; i<searchParams.length; i++)
{
var index = searchParams[i].indexOf('=');
if(index == -1)
[namedArgs setObject: "" forKey:searchParams[i]];
else
[namedArgs setObject: searchParams[i].substring(index+1) forKey: searchParams[i].substring(0, index)];
}
}
if ([args containsObject:"debug"])
CPLogRegister(CPLogPopup);
CPApp._args = args;
CPApp._namedArgs = namedArgs;
@@ -1243,6 +1224,11 @@ var _CPAppBootstrapperActions = nil;
[self performActions];
}
+ (void)cibDidFailToLoad:(CPCib)aCib
{
throw new Error("Could not load main cib file (Did you forget to nib2cib it?).");
}
+ (void)reset
{
_CPAppBootstrapperActions = nil;
+1
View File
@@ -162,6 +162,7 @@ CPGrooveBorder = 3;
[aView setFrame:CGRectInset([self bounds], _contentMargin.width + _borderWidth, _contentMargin.height + _borderWidth)];
[self replaceSubview:_contentView with:aView];
[aView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
_contentView = aView;
}
+896
View File
@@ -0,0 +1,896 @@
/*
* CPBrowser.j
* AppKit
*
* Created by Ross Boucher.
* Copyright 2010, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import "CPControl.j"
@import "CPImage.j"
@import "CPTableView.j"
@import "CPScrollView.j"
/*!
@ingroup appkit
@class CPBrowser
*/
@implementation CPBrowser : CPControl
{
id _delegate;
CPString _pathSeparator;
CPView _contentView;
CPScrollView _horizontalScrollView;
CPView _prototypeView;
CPArray _tableViews;
CPArray _tableDelegates;
id _rootItem;
BOOL _delegateSupportsImages;
SEL _doubleAction @accessors(property=doubleAction);
BOOL _allowsMultipleSelection;
BOOL _allowsEmptySelection;
Class _tableViewClass @accessors(property=tableViewClass);
float _rowHeight;
float _imageWidth;
float _leafWidth;
float _minColumnWidth;
float _defaultColumnWidth @accessors(property=defaultColumnWidth);
CPArray _columnWidths;
}
+ (CPImage)branchImage
{
return [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[self class]]
pathForResource:"browser-leaf.png"]
size:CGSizeMake(9,9)];
}
+ (CPImage)highlightedBranchImage
{
return [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[self class]]
pathForResource:"browser-leaf-highlighted.png"]
size:CGSizeMake(9,9)];
}
- (id)initWithFrame:(CGRect)aFrame
{
if (self = [super initWithFrame:aFrame])
{
_rowHeight = 23.0;
_defaultColumnWidth = 140.0;
_minColumnWidth = 80.0;
_imageWidth = 23.0;
_leafWidth = 13.0;
_columnWidths = [];
_pathSeparator = "/";
_tableViews = [];
_tableDelegates = [];
_allowsMultipleSelection = YES;
_allowsEmptySelection = YES;
_tableViewClass = [_CPBrowserTableView class];
_prototypeView = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
[_prototypeView setVerticalAlignment:CPCenterVerticalTextAlignment];
[_prototypeView setValue:[CPColor whiteColor] forThemeAttribute:"text-color" inState:CPThemeStateSelected];
[_prototypeView setLineBreakMode:CPLineBreakByTruncatingTail];
_horizontalScrollView = [[CPScrollView alloc] initWithFrame:[self bounds]];
[_horizontalScrollView setHasVerticalScroller:NO];
[_horizontalScrollView setAutohidesScrollers:YES];
[_horizontalScrollView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
_contentView = [[CPView alloc] initWithFrame:CGRectMake(0, 0, 0, CGRectGetHeight([self bounds]))];
[_contentView setAutoresizingMask:CPViewHeightSizable];
[_horizontalScrollView setDocumentView:_contentView];
[self addSubview:_horizontalScrollView];
}
return self;
}
- (void)setPrototypeView:(CPView)aPrototypeView
{
_prototypeView = [CPKeyedUnarchiver unarchiveObjectWithData:
[CPKeyedArchiver archivedDataWithRootObject:aPrototypeView]];
}
- (CPView)prototypeView
{
return [CPKeyedUnarchiver unarchiveObjectWithData:
[CPKeyedArchiver archivedDataWithRootObject:_prototypeView]];
}
- (void)setDelegate:(id)anObject
{
_delegate = anObject;
_delegateSupportsImages = [_delegate respondsToSelector:@selector(browser:imageValueForItem:)];
[self loadColumnZero];
}
- (id)delegate
{
return _delegate;
}
- (CPTableView)tableViewInColumn:(unsigned)index
{
return _tableViews[index];
}
- (unsigned)columnOfTableView:(CPTableView)aTableView
{
return [_tableViews indexOfObject:aTableView];
}
- (void)loadColumnZero
{
if ([_delegate respondsToSelector:@selector(rootItemForBrowser:)])
_rootItem = [_delegate rootItemForBrowser:self];
else
_rootItem = nil;
[self setLastColumn:-1];
[self addColumn];
}
- (void)setLastColumn:(int)columnIndex
{
if (columnIndex >= _tableViews.length)
return;
var oldValue = _tableViews.length - 1;
// unloads all later columns.
var indexPlusOne = columnIndex + 1;
[[_tableViews.slice(indexPlusOne) valueForKey:"enclosingScrollView"]
makeObjectsPerformSelector:@selector(removeFromSuperview)];
_tableViews = _tableViews.slice(0, indexPlusOne);
_tableDelegates = _tableDelegates.slice(0, indexPlusOne);
if ([_delegate respondsToSelector:@selector(browser:didChangeLastColumn:toColumn:)])
[_delegate browser:self didChangeLastColumn:oldValue toColumn:columnIndex];
[self tile];
}
- (int)lastColumn
{
return _tableViews.length - 1;
}
- (void)addColumn
{
var lastIndex = [self lastColumn],
lastColumn = _tableViews[lastIndex],
selectionIndexes = [lastColumn selectedRowIndexes];
if (lastIndex >= 0 && [selectionIndexes count] > 1)
[CPException raise:CPInvalidArgumentException
reason:"Can't add column, column "+lastIndex+" has invalid selection."];
var index = lastIndex+1,
item = index === 0 ? _rootItem : [_tableDelegates[lastIndex] childAtIndex:[selectionIndexes firstIndex]];
if (index > 0 && item && [self isLeafItem:item])
return;
var table = [[_tableViewClass alloc] initWithFrame:CGRectMakeZero() browser:self];
[table setHeaderView:nil];
[table setCornerView:nil];
[table setAllowsMultipleSelection:_allowsMultipleSelection];
[table setAllowsEmptySelection:_allowsEmptySelection];
[table registerForDraggedTypes:[self registeredDraggedTypes]];
[self setNextResponder:table];
[self _addTableColumnsToTableView:table forColumnIndex:index];
var delegate = [[_CPBrowserTableDelegate alloc] init];
[delegate _setDelegate:_delegate];
[delegate _setBrowser:self];
[delegate _setIndex:index];
[delegate _setItem:item];
_tableViews[index] = table;
_tableDelegates[index] = delegate;
[table setDelegate:delegate];
[table setDataSource:delegate];
[table setTarget:delegate];
[table setAction:@selector(_tableViewClicked:)];
[table setDoubleAction:@selector(_tableViewDoubleClicked:)];
[table setDraggingDestinationFeedbackStyle:CPTableViewDraggingDestinationFeedbackStyleRegular];
var scrollView = [[_CPBrowserScrollView alloc] initWithFrame:CGRectMakeZero()];
[scrollView _setBrowser:self];
[scrollView setDocumentView:table];
[scrollView setHasHorizontalScroller:NO];
[scrollView setAutoresizingMask:CPViewHeightSizable];
[_contentView addSubview:scrollView];
[self tile];
[self scrollColumnToVisible:index];
}
- (void)_addTableColumnsToTableView:(CPTableView)aTableView forColumnIndex:(unsigned)index
{
if (_delegateSupportsImages)
{
var column = [[CPTableColumn alloc] initWithIdentifier:@"Image"],
view = [[CPImageView alloc] initWithFrame:CGRectMakeZero()];
[view setImageScaling:CPScaleProportionally];
[column setDataView:view];
[column setResizingMask:CPTableColumnNoResizing];
[aTableView addTableColumn:column];
}
var column = [[CPTableColumn alloc] initWithIdentifier:@"Content"];
[column setDataView:_prototypeView];
[column setResizingMask:CPTableColumnNoResizing];
[aTableView addTableColumn:column];
var column = [[CPTableColumn alloc] initWithIdentifier:@"Leaf"],
view = [[_CPBrowserLeafView alloc] initWithFrame:CGRectMakeZero()];
[view setBranchImage:[[self class] branchImage]];
[view setHighlightedBranchImage:[[self class] highlightedBranchImage]];
[column setDataView:view];
[column setResizingMask:CPTableColumnNoResizing];
[aTableView addTableColumn:column];
}
- (void)reloadColumn:(int)column
{
[[self tableViewInColumn:column] reloadData];
}
- (void)tile
{
var xOrigin = 0,
scrollerWidth = [CPScroller scrollerWidth],
height = CGRectGetHeight([_contentView bounds]);
for (var i = 0, count = _tableViews.length; i < count; i++)
{
var tableView = _tableViews[i],
scrollView = [tableView enclosingScrollView],
width = [self widthOfColumn:i],
tableHeight = CGRectGetHeight([tableView bounds]);
[[tableView tableColumnWithIdentifier:"Image"] setWidth:_imageWidth];
[[tableView tableColumnWithIdentifier:"Content"] setWidth:width - (_leafWidth + _delegateSupportsImages ? _imageWidth : 0) - scrollerWidth - scrollerWidth];
[[tableView tableColumnWithIdentifier:"Leaf"] setWidth:_leafWidth];
[tableView setRowHeight:_rowHeight];
[tableView setFrameSize:CGSizeMake(width - scrollerWidth, tableHeight)];
[scrollView setFrameOrigin:CGPointMake(xOrigin, 0)];
[scrollView setFrameSize:CGSizeMake(width, height)];
xOrigin += width;
}
[_contentView setFrameSize:CGSizeMake(xOrigin, height)];
}
// ITEMS
- (id)itemAtRow:(int)row inColumn:(int)column
{
return [_tableDelegates[column] childAtIndex:row];
}
- (BOOL)isLeafItem:(id)item
{
return [_delegate respondsToSelector:@selector(browser:isLeafItem:)] && [_delegate browser:self isLeafItem:item];
}
- (id)parentForItemsInColumn:(int)column
{
return [_tableDelegates[column] _item];
}
- (CPSet)selectedItems
{
var selectedColumn = [self selectedColumn],
selectedIndexes = [self selectedRowIndexesInColumn:selectedColumn],
set = [CPSet set],
index = [selectedIndexes firstIndex];
while (index !== CPNotFound)
{
[set addObject:[self itemAtRow:index inColumn:selectedColumn]];
index = [selectedIndexes indexGreaterThanIndex:index];
}
return set;
}
- (id)selectedItem
{
var selectedColumn = [self selectedColumn],
selectedRow = [self selectedRowInColumn:selectedColumn];
return [self itemAtRow:selectedRow inColumn:selectedColumn];
}
// CLICK EVENTS
- (void)_column:(unsigned)columnIndex clickedRow:(unsigned)rowIndex
{
[self setLastColumn:columnIndex];
if (rowIndex >= 0)
[self addColumn];
[self doClick:self];
}
- (void)sendAction
{
[self sendAction:_action to:_target];
}
- (void)doClick:(id)sender
{
[self sendAction:_action to:_target];
}
- (void)doDoubleClick:(id)sender
{
[self sendAction:_doubleAction to:_target];
}
// SIZING
- (float)columnContentWidthForColumnWidth:(float)aWidth
{
return aWidth - (_leafWidth + _delegateSupportsImages ? _imageWidth : 0) - [CPScroller scrollerWidth];
}
- (float)columnWidthForColumnContentWidth:(float)aWidth
{
return aWidth + (_leafWidth + _delegateSupportsImages ? _imageWidth : 0) + [CPScroller scrollerWidth];
}
- (void)setImageWidth:(float)aWidth
{
_imageWidth = aWidth;
[self tile];
}
- (float)imageWidth
{
return _imageWidth;
}
- (void)setMinColumnWidth:(float)minWidth
{
_minColumnWidth = minWidth;
[self tile];
}
- (float)minColumnWidth
{
return _minColumnWidth;
}
- (void)setWidth:(float)aWidth ofColumn:(unsigned)column
{
_columnWidths[column] = aWidth;
if ([_delegate respondsToSelector:@selector(browser:didResizeColumn:)])
[_delegate browser:self didResizeColumn:column];
[self tile];
}
- (float)widthOfColumn:(unsigned)column
{
var width = _columnWidths[column];
if (width == null)
width = _defaultColumnWidth;
return MAX([CPScroller scrollerWidth], MAX(_minColumnWidth, width));
}
- (void)setRowHeight:(float)aHeight
{
_rowHeight = aHeight;
}
- (float)rowHeight
{
return _rowHeight;
}
// SCROLLERS
- (void)scrollColumnToVisible:(unsigned)columnIndex
{
[_contentView scrollRectToVisible:[[[self tableViewInColumn:columnIndex] enclosingScrollView] frame]];
}
(void)scrollRowToVisible:(unsigned)rowIndex inColumn:(unsigned)columnIndex
{
[self scrollColumnToVisible:columnIndex];
[[self tableViewInColumn:columnIndex] scrollRowToVisible:rowIndex];
}
- (BOOL)autohidesScroller
{
return [_horizontalScrollView autohidesScrollers];
}
- (void)setAutohidesScroller:(BOOL)shouldHide
{
[_horizontalScrollView setAutohidesScrollers:shouldHide];
}
// SELECTION
- (unsigned)selectedRowInColumn:(unsigned)columnIndex
{
if (columnIndex > [self lastColumn] || columnIndex < 0)
return -1;
return [_tableViews[columnIndex] selectedRow];
}
- (unsigned)selectedColumn
{
var column = [self lastColumn],
row = [self selectedRowInColumn:column];
if (row >= 0)
return column;
else
return column - 1;
}
- (void)selectRow:(unsigned)row inColumn:(unsigned)column
{
var selectedIndexes = row === -1 ? [CPIndexSet indexSet] : [CPIndexSet indexSetWithIndex:row];
[self selectRowIndexes:selectedIndexes inColumn:column];
}
- (BOOL)allowsMultipleSelection
{
return _allowsMultipleSelection;
}
- (void)setAllowsMultipleSelection:(BOOL)shouldAllow
{
if (_allowsMultipleSelection === shouldAllow)
return;
_allowsMultipleSelection = shouldAllow;
[_tableViews makeObjectsPerformSelector:@selector(setAllowsMultipleSelection:) withObject:shouldAllow];
}
- (BOOL)allowsEmptySelection
{
return _allowsEmptySelection;
}
- (void)setAllowsEmptySelection:(BOOL)shouldAllow
{
if (_allowsEmptySelection === shouldAllow)
return;
_allowsEmptySelection = shouldAllow;
[_tableViews makeObjectsPerformSelector:@selector(setAllowsEmptySelection:) withObject:shouldAllow];
}
- (CPIndexSet)selectedRowIndexesInColumn:(unsigned)column
{
return [[self tableViewInColumn:column] selectedRowIndexes];
}
- (void)selectRowIndexes:(CPIndexSet)indexSet inColumn:(unsigned)column
{
if (column < 0 || column > [self lastColumn] + 1)
return;
if ([_delegate respondsToSelector:@selector(browser:selectionIndexesForProposedSelection:inColumn:)])
indexSet = [_delegate browser:self selectionIndexesForProposedSelection:indexSet inColumn:column];
if ([_delegate respondsToSelector:@selector(browser:shouldSelectRowIndexes:inColumn:)] &&
![_delegate browser:self shouldSelectRowIndexes:indexSet inColumn:column])
return;
if ([_delegate respondsToSelector:@selector(browserSelectionIsChanging:)])
[_delegate browserSelectionIsChanging:self];
if (column > [self lastColumn])
[self addColumn];
[self setLastColumn:column];
[[self tableViewInColumn:column] selectRowIndexes:indexSet byExtendingSelection:NO];
[self setNextResponder:[self tableViewInColumn:[self lastColumn]]];
[self scrollColumnToVisible:column];
if ([_delegate respondsToSelector:@selector(browserSelectionDidChange:)])
[_delegate browserSelectionDidChange:self];
}
- (void)setBackgroundColor:(CPColor)aColor
{
[super setBackgroundColor:aColor];
[_contentView setBackgroundColor:aColor];
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
// DRAG AND DROP
- (void)registerForDraggedTypes:(CPArray)types
{
[super registerForDraggedTypes:types];
[_tableViews makeObjectsPerformSelector:@selector(registerForDraggedTypes:) withObject:types];
}
- (BOOL)canDragRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(int)columnIndex withEvent:(CPEvent)dragEvent
{
if ([_delegate respondsToSelector:@selector(browser:canDragRowsWithIndexes:inColumn:withEvent:)])
return [_delegate browser:self canDragRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent];
return YES;
}
- (CPImage)draggingImageForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(int)columnIndex withEvent:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
{
if ([_delegate respondsToSelector:@selector(browser:draggingImageForRowsWithIndexes:inColumn:withEvent:offset:)])
return [_delegate browser:self draggingImageForRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent offset:dragImageOffset];
return nil;
}
- (CPView)draggingViewForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(int)columnIndex withEvent:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
{
if ([_delegate respondsToSelector:@selector(browser:draggingViewForRowsWithIndexes:inColumn:withEvent:offset:)])
return [_delegate browser:self draggingViewForRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent offset:dragImageOffset];
return nil;
}
@end
@implementation _CPBrowserResizeControl : CPView
{
CGPoint _mouseDownX;
CPBrowser _browser;
unsigned _index;
unsigned _width;
}
- (void)mouseDown:(CPEvent)anEvent
{
_mouseDownX = [anEvent locationInWindow].x;
_browser = [[self superview] _browser];
_index = [_browser columnOfTableView:[[self superview] documentView]];
_width = [_browser widthOfColumn:_index];
}
- (void)mouseDragged:(CPEvent)anEvent
{
var deltaX = [anEvent locationInWindow].x - _mouseDownX;
[_browser setWidth:_width + deltaX ofColumn:_index];
}
@end
var _CPBrowserResizeControlBackgroundImage = nil;
@implementation _CPBrowserScrollView : CPScrollView
{
_CPBrowserResizeControl _resizeControl;
CPBrowser _browser @accessors;
}
+ (CPImage)backgroundImage
{
if (!_CPBrowserResizeControlBackgroundImage)
{
var path = [[CPBundle bundleForClass:[self class]] pathForResource:"browser-resize-control.png"];
_CPBrowserResizeControlBackgroundImage = [[CPImage alloc] initWithContentsOfFile:path
size:CGSizeMake(15, 14)];
}
return _CPBrowserResizeControlBackgroundImage;
}
- (void)initWithFrame:(CGRect)aFrame
{
if (self = [super initWithFrame:aFrame])
{
_resizeControl = [[_CPBrowserResizeControl alloc] initWithFrame:CGRectMakeZero()];
[_resizeControl setBackgroundColor:[CPColor colorWithPatternImage:[[self class] backgroundImage]]];
[self addSubview:_resizeControl];
}
return self;
}
- (void)reflectScrolledClipView:(CPClipView)aClipView
{
[super reflectScrolledClipView:aClipView];
var frame = [_verticalScroller frame];
frame.size.height = CGRectGetHeight([self bounds]) - 14.0 - frame.origin.y;
[_verticalScroller setFrameSize:frame.size];
var resizeFrame = CGRectMake(CGRectGetMinX(frame), CGRectGetMaxY(frame), [CPScroller scrollerWidth], 14.0);
[_resizeControl setFrame:resizeFrame];
}
@end
@implementation _CPBrowserTableView : CPTableView
{
CPBrowser _browser;
}
- (id)initWithFrame:(CGRect)aFrame browser:(CPBrowser)aBrowser
{
if (self = [super initWithFrame:aFrame])
_browser = aBrowser;
return self;
}
- (BOOL)acceptsFirstResponder
{
return NO;
}
- (void)mouseDown:(CPEvent)anEvent
{
[super mouseDown:anEvent];
[[self window] makeFirstResponder:_browser];
}
- (CPView)browserView
{
return _browser;
}
- (BOOL)canDragRowsWithIndexes:(CPIndexSet)rowIndexes atPoint:(CGPoint)mouseDownPoint
{
return [_browser canDragRowsWithIndexes:rowIndexes inColumn:[_browser columnOfTableView:self] withEvent:[CPApp currentEvent]];
}
- (CPImage)dragImageForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CPPointPointer)dragImageOffset
{
return [_browser draggingImageForRowsWithIndexes:dragRows inColumn:[_browser columnOfTableView:self] withEvent:dragEvent offset:dragImageOffset] ||
[super dragImageForRowsWithIndexes:dragRows tableColumns:theTableColumns event:dragEvent offset:dragImageOffset];
}
- (CPView)dragViewForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CPPoint)dragViewOffset
{
var count = theTableColumns.length;
while (count--)
{
if ([theTableColumns[count] identifier] === "Leaf")
[theTableColumns removeObject:theTableColumns[count]];
}
return [_browser draggingViewForRowsWithIndexes:dragRows inColumn:[_browser columnOfTableView:self] withEvent:dragEvent offset:dragViewOffset] ||
[super dragViewForRowsWithIndexes:dragRows tableColumns:theTableColumns event:dragEvent offset:dragViewOffset];
}
- (void)moveUp:(id)sender
{
[super moveUp:sender];
[_browser selectRow:[self selectedRow] inColumn:[_browser selectedColumn]];
}
- (void)moveDown:(id)sender
{
[super moveDown:sender];
[_browser selectRow:[self selectedRow] inColumn:[_browser selectedColumn]];
}
- (void)moveLeft:(id)sender
{
var previousColumn = [_browser selectedColumn] - 1,
selectedRow = [_browser selectedRowInColumn:previousColumn];
[_browser selectRow:selectedRow inColumn:previousColumn];
}
- (void)moveRight:(id)sender
{
[_browser selectRow:0 inColumn:[_browser selectedColumn] + 1];
}
@end
@implementation _CPBrowserTableDelegate : CPObject
{
CPBrowser _browser @accessors;
unsigned _index @accessors;
id _delegate @accessors;
id _item @accessors;
}
- (unsigned)numberOfRowsInTableView:(CPTableView)aTableView
{
return [_delegate browser:_browser numberOfChildrenOfItem:_item];
}
- (void)tableView:(CPTableView)aTableView objectValueForTableColumn:(CPTableColumn)column row:(unsigned)row
{
if ([column identifier] === "Image")
return [_delegate browser:_browser imageValueForItem:[self childAtIndex:row]];
else if ([column identifier] === "Leaf")
return ![_browser isLeafItem:[self childAtIndex:row]];
else
return [_delegate browser:_browser objectValueForItem:[self childAtIndex:row]];
}
- (void)_tableViewDoubleClicked:(CPTableView)aTableView
{
[_browser doDoubleClick:self];
}
- (void)_tableViewClicked:(CPTableView)aTableView
{
var selectedIndexes = [aTableView selectedRowIndexes];
[_browser _column:_index clickedRow:[selectedIndexes count] === 1 ? [selectedIndexes firstIndex] : -1];
}
- (id)childAtIndex:(unsigned)index
{
return [_delegate browser:_browser child:index ofItem:_item];
}
- (BOOL)tableView:(CPTableView)aTableView acceptDrop:(id)info row:(int)row dropOperation:(CPTableViewDropOperation)operation
{
if ([_delegate respondsToSelector:@selector(browser:acceptDrop:atRow:column:dropOperation:)])
return [_delegate browser:_browser acceptDrop:info atRow:row column:_index dropOperation:operation];
else
return NO;
}
- (CPDragOperation)tableView:(CPTableView)aTableView validateDrop:(id)info proposedRow:(int)row proposedDropOperation:(CPTableViewDropOperation)operation
{
if ([_delegate respondsToSelector:@selector(browser:validateDrop:proposedRow:column:dropOperation:)])
[_delegate browser:_browser validateDrop:info proposedRow:row column:_index dropOperation:operation];
else
return CPDragOperationNone;
}
- (BOOL)tableView:(CPTableView)aTableView writeRowsWithIndexes:(CPIndexSet)rowIndexes toPasteboard:(CPPasteboard)pboard
{
if ([_delegate respondsToSelector:@selector(browser:writeRowsWithIndexes:inColumn:toPasteboard:)])
return [_delegate browser:_browser writeRowsWithIndexes:rowIndexes inColumn:_index toPasteboard:pboard];
else
return NO;
}
- (BOOL)respondsToSelector:(SEL)aSelector
{
if (aSelector === @selector(browser:writeRowsWithIndexes:inColumn:toPasteboard:))
return [_delegate respondsToSelector:@selector(browser:writeRowsWithIndexes:inColumn:toPasteboard:)];
else
return [super respondsToSelector:aSelector];
}
@end
@implementation _CPBrowserLeafView : CPView
{
BOOL _isLeaf @accessors(readonly, property=isLeaf);
CPImage _branchImage @accessors(property=branchImage);
CPImage _highlightedBranchImage @accessors(property=highlightedBranchImage);
}
- (BOOL)objectValue
{
return _isLeaf;
}
- (void)setObjectValue:(id)aValue
{
_isLeaf = !!aValue;
[self setNeedsLayout];
}
- (CGRect)rectForEphemeralSubviewNamed:(CPString)aName
{
if (aName === "image-view")
return CGRectInset([self bounds], 1, 1);
return [super rectForEphemeralSubviewNamed:aName];
}
- (CPView)createEphemeralSubviewNamed:(CPString)aName
{
if (aName === "image-view")
return [[CPImageView alloc] initWithFrame:CGRectMakeZero()];
return [super createEphemeralSubviewNamed:aName];
}
- (void)layoutSubviews
{
var imageView = [self layoutEphemeralSubviewNamed:@"image-view"
positioned:CPWindowAbove
relativeToEphemeralSubviewNamed:nil];
var isHighlighted = [self themeState] & CPThemeStateSelected;
[imageView setImage: _isLeaf ? (isHighlighted ? _highlightedBranchImage : _branchImage) : nil];
[imageView setImageScaling:CPScaleNone];
}
- (void)encodeWithCoder:(CPCoder)aCoder
{
[super encodeWithCoder:aCoder];
[aCoder encodeBool:_isLeaf forKey:"_CPBrowserLeafViewIsLeafKey"];
[aCoder encodeObject:_branchImage forKey:"_CPBrowserLeafViewBranchImageKey"];
[aCoder encodeObject:_highlightedBranchImage forKey:"_CPBrowserLeafViewHighlightedBranchImageKey"];
}
- (void)initWithCoder:(CPCoder)aCoder
{
if (self = [super initWithCoder:aCoder])
{
_isLeaf = [aCoder decodeBoolForKey:"_CPBrowserLeafViewIsLeafKey"];
_branchImage = [aCoder decodeObjectForKey:"_CPBrowserLeafViewBranchImageKey"];
_highlightedBranchImage = [aCoder decodeObjectForKey:"_CPBrowserLeafViewHighlightedBranchImageKey"];
}
return self;
}
@end
+2 -5
View File
@@ -502,8 +502,6 @@ CPButtonStateMixed = CPThemeState("mixed");
}
else
return [[_CPImageAndTextView alloc] initWithFrame:_CGRectMakeZero()];
return [super createEphemeralSubviewNamed:aName];
}
- (void)layoutSubviews
@@ -511,9 +509,8 @@ CPButtonStateMixed = CPThemeState("mixed");
var bezelView = [self layoutEphemeralSubviewNamed:@"bezel-view"
positioned:CPWindowBelow
relativeToEphemeralSubviewNamed:@"content-view"];
if (bezelView)
[bezelView setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
[bezelView setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
var contentView = [self layoutEphemeralSubviewNamed:@"content-view"
positioned:CPWindowAbove
+208 -30
View File
@@ -4,18 +4,33 @@
#include "CoreGraphics/CGGeometry.h"
@implementation CPButtonBar : CPControl
@implementation CPButtonBar : CPView
{
BOOL _hasResizeControl;
BOOL _resizeControlIsLeftAligned;
CPArray _buttons;
}
- (id)initWithFrame:(CGRect)aFrame
+ (id)plusButton
{
self = [super initWithFrame:aFrame];
var button = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, 35, 25)],
image = [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:self] pathForResource:@"plus_button.png"] size:CGSizeMake(11, 12)];
if (self)
[self setNeedsLayout];
[button setImage:image];
[button setImagePosition:CPImageOnly];
return self;
return button;
}
+ (id)minusButton
{
var button = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, 35, 25)],
image = [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:self] pathForResource:@"minus_button.png"] size:CGSizeMake(11, 4)];
[button setImage:image];
[button setImagePosition:CPImageOnly];
return button;
}
+ (CPString)themeClass
@@ -25,47 +40,210 @@
+ (id)themeAttributes
{
return [CPDictionary dictionaryWithObjects:[[CPNull null]]
forKeys:[@"bezel-color"]];
return [CPDictionary dictionaryWithObjects:[CGInsetMake(0.0, 0.0, 0.0, 0.0), CGSizeMakeZero(), [CPNull null], [CPNull null], [CPNull null]]
forKeys:[@"resize-control-inset", @"resize-control-size", @"resize-control-color", @"bezel-color", @"button-bezel-color"]];
}
- (id)initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self)
{
_buttons = [];
[self setNeedsLayout];
}
return self;
}
- (void)awakeFromCib
{
var view = [self superview],
subview = self;
while (view)
{
if ([view isKindOfClass:[CPSplitView class]])
{
var viewIndex = [[view subviews] indexOfObject:subview];
[view setButtonBar:self forDividerAtIndex:viewIndex];
break;
}
subview = view;
view = [view superview];
}
}
- (void)setButtons:(CPArray)buttons
{
_buttons = [CPArray arrayWithArray:buttons];
for (var i = 0, count = [_buttons count]; i < count; i++)
{
var button = _buttons[i];
var normalColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateNormal],
highlightedColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateHighlighted],
disabledColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateDisabled];
[button setValue:normalColor forThemeAttribute:@"bezel-color" inState:CPThemeStateNormal|CPThemeStateBordered];
[button setValue:highlightedColor forThemeAttribute:@"bezel-color" inState:CPThemeStateHighlighted|CPThemeStateBordered];
[button setValue:disabledColor forThemeAttribute:@"bezel-color" inState:CPThemeStateDisabled|CPThemeStateBordered];
// FIXME shouldn't need this
[button setValue:normalColor forThemeAttribute:@"bezel-color" inState:CPThemeStateNormal|CPThemeStateBordered|CPPopUpButtonStatePullsDown];
[button setValue:highlightedColor forThemeAttribute:@"bezel-color" inState:CPThemeStateHighlighted|CPThemeStateBordered|CPPopUpButtonStatePullsDown];
[button setValue:disabledColor forThemeAttribute:@"bezel-color" inState:CPThemeStateDisabled|CPThemeStateBordered|CPPopUpButtonStatePullsDown];
[button setBordered:YES];
}
[self setNeedsLayout];
}
- (CPArray)buttons
{
return [CPArray arrayWithArray:_buttons];
}
- (void)setHasResizeControl:(BOOL)shouldHaveResizeControl
{
if (_hasResizeControl === shouldHaveResizeControl)
return;
_hasResizeControl = !!shouldHaveResizeControl;
[self setNeedsLayout];
}
- (BOOL)hasResizeControl
{
return _hasResizeControl;
}
- (void)setResizeControlIsLeftAligned:(BOOL)shouldBeLeftAligned
{
if (_resizeControlIsLeftAligned === shouldBeLeftAligned)
return;
_resizeControlIsLeftAligned = !!shouldBeLeftAligned;
[self setNeedsLayout];
}
- (BOOL)resizeControlIsLeftAligned
{
return _resizeControlIsLeftAligned;
}
- (CGRect)resizeControlFrame
{
var inset = [self currentValueForThemeAttribute:@"resize-control-inset"],
size = [self currentValueForThemeAttribute:@"resize-control-size"],
currentSize = [self bounds],
leftOrigin = _resizeControlIsLeftAligned ? 0 : currentSize.size.width - size.width - inset.right - inset.left;
return CGRectMake(leftOrigin, 0, size.width + inset.left + inset.right, size.height + inset.top + inset.bottom);
}
- (CGRect)rectForEphemeralSubviewNamed:(CPString)aName
{
if (aName === "bezel-view")
return [self bounds];
if (aName === "resize-control-view")
{
var inset = [self currentValueForThemeAttribute:@"resize-control-inset"],
size = [self currentValueForThemeAttribute:@"resize-control-size"],
currentSize = [self bounds];
if (_resizeControlIsLeftAligned)
return CGRectMake(inset.left, inset.top, size.width, size.height);
else
return CGRectMake(currentSize.size.width - size.width - inset.right, inset.top, size.width, size.height);
}
return [super rectForEphemeralSubviewNamed:aName];
}
- (CPView)createEphemeralSubviewNamed:(CPString)aName
{
if (aName === "bezel-view")
{
var view = [[CPView alloc] initWithFrame:_CGRectMakeZero()];
if (aName === "resize-control-view")
return [[CPView alloc] initWithFrame:CGRectMakeZero()];
[view setHitTests:NO];
return view;
}
return [super createEphemeralSubviewNamed:aName];
}
- (void)layoutSubviews
{
var bezelView = [self layoutEphemeralSubviewNamed:@"bezel-view"
positioned:CPWindowBelow
relativeToEphemeralSubviewNamed:@""];
if (bezelView)
[bezelView setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
}
[self setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
- (void)addSubview:(CPView)aSubview
{
[super addSubview:aSubview];
var buttonsNotHidden = [CPArray arrayWithArray:_buttons],
count = [buttonsNotHidden count];
[aSubview setAutoresizingMask:CPViewMinXMargin];
while (count--)
if ([buttonsNotHidden[count] isHidden])
[buttonsNotHidden removeObject:buttonsNotHidden[count]];
var currentButtonOffset = _resizeControlIsLeftAligned ? CGRectGetMaxX([self bounds]) + 1 : -1,
height = CGRectGetHeight([self bounds]) - 1;
for (var i = 0, count = [buttonsNotHidden count]; i < count; i++)
{
var button = buttonsNotHidden[i],
width = CGRectGetWidth([button frame]);
if (_resizeControlIsLeftAligned)
{
[button setFrame:CGRectMake(currentButtonOffset - width, 1, width, height)];
currentButtonOffset -= width - 1;
}
else
{
[button setFrame:CGRectMake(currentButtonOffset, 1, width, height)];
currentButtonOffset += width - 1;
}
[self addSubview:button];
}
if (_hasResizeControl)
{
var resizeControlView = [self layoutEphemeralSubviewNamed:@"resize-control-view"
positioned:CPWindowAbove
relativeToEphemeralSubviewNamed:nil];
[resizeControlView setAutoresizingMask: _resizeControlIsLeftAligned ? CPViewMaxXMargin : CPViewMinXMargin];
[resizeControlView setBackgroundColor:[self currentValueForThemeAttribute:@"resize-control-color"]];
}
}
@end
var CPButtonBarHasResizeControlKey = @"CPButtonBarHasResizeControlKey",
CPButtonBarResizeControlIsLeftAlignedKey = @"CPButtonBarResizeControlIsLeftAlignedKey",
CPButtonBarButtonsKey = @"CPButtonBarButtonsKey";
@implementation CPButtonBar (CPCoding)
- (void)encodeWithCoder:(CPCoder)aCoder
{
[super encodeWithCoder:aCoder];
[aCoder encodeBool:_hasResizeControl forKey:CPButtonBarHasResizeControlKey];
[aCoder encodeBool:_resizeControlIsLeftAligned forKey:CPButtonBarResizeControlIsLeftAlignedKey];
[aCoder encodeObject:_buttons forKey:CPButtonBarButtonsKey];
}
- (id)initWithCoder:(CPCoder)aCoder
{
if (self = [super initWithCoder:aCoder])
{
_buttons = [aCoder decodeObjectForKey:CPButtonBarButtonsKey] || [];
_hasResizeControl = [aCoder decodeBoolForKey:CPButtonBarHasResizeControlKey];
_resizeControlIsLeftAligned = [aCoder decodeBoolForKey:CPButtonBarResizeControlIsLeftAlignedKey];
}
return self;
}
@end
+14 -6
View File
@@ -120,9 +120,13 @@
[super setBoundsOrigin:aPoint];
var superview = [self superview];
if([superview isKindOfClass:[CPScrollView class]])
var superview = [self superview],
// This is hack to avoid having to import CPScrollView.
// FIXME: Should CPScrollView be finding out about this on its own somehow?
scrollViewClass = objj_getClass("CPScrollView");
if([superview isKindOfClass:scrollViewClass])
[superview reflectScrolledClipView:self];
}
@@ -173,9 +177,13 @@
return;
// ... and we're in a scroll view of course.
var superview = [self superview];
if ([superview isKindOfClass:[CPScrollView class]])
var superview = [self superview],
// This is hack to avoid having to import CPScrollView.
// FIXME: Should CPScrollView be finding out about this on its own somehow?
scrollViewClass = objj_getClass("CPScrollView");
if ([superview isKindOfClass:scrollViewClass])
[superview reflectScrolledClipView:self];
}
+55 -30
View File
@@ -597,6 +597,10 @@
if (![_selectionIndexes count])
return;
if ([_delegate respondsToSelector:@selector(collectionView:canDragItemsAtIndexes:withEvent:)] &&
![_delegate collectionView:self canDragItemsAtIndexes:_selectionIndexes withEvent:_mouseDownEvent])
return;
// Set up the pasteboard
var dragTypes = [_delegate collectionView:self dragTypesForItemsAtIndexes:_selectionIndexes];
@@ -676,41 +680,42 @@
return _delegate;
}
- (CPCollectionViewItem)itemAtIndex:(unsigned)anIndex
{
return [_items objectAtIndex:anIndex];
}
- (CGRect)frameForItemAtIndex:(unsigned)anIndex
{
return [[[self itemAtIndex:anIndex] view] frame];
}
- (CGRect)frameForItemsAtIndexes:(CPIndexSet)anIndexSet
{
var indexArray = [],
frame = CGRectNull;
[anIndexSet getIndexes:indexArray maxCount:-1 inIndexRange:nil];
var index = 0,
count = [indexArray count];
for (; index < count; ++index)
frame = CGRectUnion(frame, [self rectForItemAtIndex:indexArray[index]]);
return frame;
}
@end
@implementation CPCollectionView (KeyboardInteraction)
- (CGRect)rectForItemAtIndex:(int)index
{
// Don't re-compute anything just grab the current frame
// This allows subclasses to override tile without messing this up.
return [[_items[index] view] frame];
}
- (CGRect)rectForItemsAtIndexes:(CPIndexSet)indexSet
{
var indexArray = [],
rect = nil;
[indexSet getIndexes:indexArray maxCount:-1 inIndexRange:nil];
for (var i = 0, count = indexArray.length; i < count; ++i)
{
var index = indexArray[i];
if (rect == nil)
rect = [self rectForItemAtIndex:index];
else
rect = CGRectUnion(rect, [self rectForItemAtIndex:index]);
}
return rect;
}
- (void)_scrollToSelection
{
var rect = [self rectForItemsAtIndexes:[self selectionIndexes]];
if (rect)
[self scrollRectToVisible:rect];
var frame = [self frameForItemsAtIndexes:[self selectionIndexes]];
if (!CGRectIsNull(frame))
[self scrollRectToVisible:frame];
}
- (void)moveLeft:(id)sender
@@ -753,7 +758,7 @@
[self _scrollToSelection];
}
- (void)deleteBackwards:(id)sender
- (void)deleteBackward:(id)sender
{
if ([[self delegate] respondsToSelector:@selector(collectionView:shouldDeleteItemsAtIndexes:)])
{
@@ -775,6 +780,26 @@
@end
@implementation CPCollectionView (Deprecated)
- (CGRect)rectForItemAtIndex:(int)anIndex
{
_CPReportLenientDeprecation([self class], _cmd, @selector(frameForItemAtIndex:));
// Don't re-compute anything just grab the current frame
// This allows subclasses to override tile without messing this up.
return [self frameForItemAtIndex:anIndex];
}
- (CGRect)rectForItemsAtIndexes:(CPIndexSet)anIndexSet
{
_CPReportLenientDeprecation([self class], _cmd, @selector(frameForItemsAtIndexes:));
return [self frameForItemsAtIndexes:anIndexSet];
}
@end
var CPCollectionViewMinItemSizeKey = @"CPCollectionViewMinItemSizeKey",
CPCollectionViewMaxItemSizeKey = @"CPCollectionViewMaxItemSizeKey",
CPCollectionViewVerticalMarginKey = @"CPCollectionViewVerticalMarginKey",
+11 -57
View File
@@ -437,51 +437,16 @@ var cachedBlackColor,
if (self)
{
_components = components;
if (!CPFeatureIsCompatible(CPCSSRGBAFeature) && _components[3] != 1.0 && window.Base64 && window.CRC32)
{
var bytes = [0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,0x8,0x3,0x0,0x0,0x0,0x28,0xcb,0x34,0xbb,0x0,0x0,0x3,0x0,0x50,0x4c,0x54,0x45,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x17,0x89,0x99,0x55,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x10,0x49,0x44,0x41,0x54,0x78,0xda,0x62,0x60,0x0,0x0,0x0,0x0,0xff,0xff,0x3,0x0,0x0,0x2,0x0,0x1,0x24,0x7f,0x24,0xf1,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,0xff];
var r_off = 41;
var g_off = 42;
var b_off = 43;
var a_off = 821;
var plte_crc_off = 809;
var trns_crc_off = 822;
var plte_type_off = 37;
var trns_type_off = 817;
bytes[r_off] = Math.round(_components[0]*255);
bytes[g_off] = Math.round(_components[1]*255);
bytes[b_off] = Math.round(_components[2]*255);
bytes[a_off] = Math.round(_components[3]*255);
// calculate new CRCs
var new_plte_crc = integerToBytes(CRC32.getCRC(bytes, plte_type_off, 4+768), 4);
var new_trns_crc = integerToBytes(CRC32.getCRC(bytes, trns_type_off, 4+1), 4);
// overwrite old CRCs with new ones
for (var i = 0; i < 4; i++)
{
bytes[plte_crc_off+i] = new_plte_crc[i];
bytes[trns_crc_off+i] = new_trns_crc[i];
}
// Base64 encode, strip whitespace and build data URL
var base64image = Base64.encode(bytes); //.replace(/[\s]/g, "");
_cssString = "url(\"data:image/png;base64," + base64image + "\")";
}
else
{
var hasAlpha = CPFeatureIsCompatible(CPCSSRGBAFeature) && _components[3] != 1.0;
_cssString = (hasAlpha ? "rgba(" : "rgb(") +
parseInt(_components[0] * 255.0) + ", " +
parseInt(_components[1] * 255.0) + ", " +
parseInt(_components[2] * 255.0) +
(hasAlpha ? (", " + _components[3]) : "") + ")";
}
var hasAlpha = CPFeatureIsCompatible(CPCSSRGBAFeature) && _components[3] != 1.0;
_cssString = (hasAlpha ? "rgba(" : "rgb(") +
parseInt(_components[0] * 255.0) + ", " +
parseInt(_components[1] * 255.0) + ", " +
parseInt(_components[2] * 255.0) +
(hasAlpha ? (", " + _components[3]) : "") + ")";
}
return self;
}
@@ -494,6 +459,7 @@ var cachedBlackColor,
{
_patternImage = anImage;
_cssString = "url(\"" + [_patternImage filename] + "\")";
_components = [0.0, 0.0, 0.0, 1.0];
}
return self;
@@ -736,7 +702,7 @@ var CPColorComponentsKey = @"CPColorComponentsKey",
var hexCharacters = "0123456789ABCDEF";
// HACK: prevent these from becoming globals. workaround for obj-j "function foo(){}" behavior
var hexToRGB, integerToBytes, rgbToHex, byteToHex;
var hexToRGB, rgbToHex, byteToHex;
/*!
Used for the CPColor \c +colorWithHexString: implementation
@@ -764,18 +730,6 @@ function hexToRGB(hex)
return [red, green, blue, 1.0];
}
function integerToBytes(integer, length) {
if (!length)
length = (integer == 0) ? 1 : Math.round((Math.log(integer)/Math.log(2))/8+0.5);
var bytes = new Array(length);
for (var i = length-1; i >= 0; i--) {
bytes[i] = integer & 255;
integer = integer >> 8
}
return bytes;
}
function rgbToHex(r,g,b) {
return byteToHex(r) + byteToHex(g) + byteToHex(b);
}
+1 -1
View File
@@ -51,7 +51,7 @@ var CPSharedFontManager = nil,
// Changing the Default Font Conversion Classes
/*!
Sets the class that will be used to create the applcation's
Sets the class that will be used to create the application's
font manager.
*/
+ (void)setFontManagerFactory:(Class)aClass
+3
View File
@@ -370,7 +370,10 @@ var LEFT_SHADOW_INSET = 3.0,
var images = [CPKeyedUnarchiver unarchiveObjectWithData:[[aSender draggingPasteboard] dataForType:CPImagesPboardType]];
if ([images count])
{
[self setImage:images[0]];
[self sendAction:[self action] to:[self target]];
}
}
@end
+2 -2
View File
@@ -227,8 +227,8 @@ var SelectionColor = nil,
CGContextClosePath(context);
CGContextSetShadowWithColor(context, CGSizeMake(0.0, 1.0), 1.1, _shadowColor);
CGContextSetFillColor(context, _color);
CGContextSetShadowWithColor(context, CGSizeMake(0.0, 1.0), 1.1, _shadowColor || [CPColor whiteColor]);
CGContextSetFillColor(context, _color || [CPColor blackColor]);
CGContextFillPath(context);
}
+13 -3
View File
@@ -52,9 +52,10 @@ var CPOutlineViewDataSource_outlineView_setObjectValue_forTableColumn_byItem_
var CPOutlineViewDelegate_outlineView_dataViewForTableColumn_item_ = 1 << 1,
CPOutlineViewDelegate_outlineView_shouldSelectItem_ = 1 << 2;
CPOutlineViewDelegate_outlineView_shouldSelectItem_ = 1 << 2,
CPOutlineViewDelegate_outlineView_heightOfRowByItem_ = 1 << 3,
CPOutlineViewDelegate_outlineView_willDisplayView_forTableColumn_item_ = 1 << 4;
CPOutlineViewDelegate_outlineView_willDisplayView_forTableColumn_item_ = 1 << 4,
CPOutlineViewDelegate_outlineView_isGroupItem_ = 1 << 5;
CPOutlineViewDropOnItemIndex = -1;
@@ -468,7 +469,10 @@ CPOutlineViewDropOnItemIndex = -1;
if ([_outlineViewDelegate respondsToSelector:@selector(outlineView:willDisplayView:forTableColumn:item:)])
_implementedOutlineViewDelegateMethods |= CPOutlineViewDelegate_outlineView_willDisplayView_forTableColumn_item_;
if ([_outlineViewDelegate respondsToSelector:@selector(outlineView:isGroupItem:)])
_implementedOutlineViewDelegateMethods |= CPOutlineViewDelegate_outlineView_isGroupItem_;
if ([_outlineViewDelegate respondsToSelector:@selector(outlineViewColumnDidMove:)])
[defaultCenter
addObserver:_outlineViewDelegate
@@ -1020,7 +1024,13 @@ var _loadItemInfoForItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anIt
}
}
- (BOOL)tableView:(CPTableView)aTableView isGroupRow:(int)row
{
if ((_outlineView._implementedOutlineViewDelegateMethods & CPOutlineViewDelegate_outlineView_isGroupItem_))
return [_outlineView._outlineViewDelegate outlineView:_outlineView isGroupItem:[_outlineView itemAtRow:theRow]];
return NO;
}
@end
+18
View File
@@ -152,6 +152,15 @@ CPDownArrowKeyCode = 40;
[_nextResponder performSelector:_cmd withObject:anEvent];
}
/*!
Notifies the receiver that the user has clicked the right mouse down in its area.
@param anEvent contains information about the right click
*/
- (void)rightMouseDown:(CPEvent)anEvent
{
[_nextResponder performSelector:_cmd withObject:anEvent];
}
/*!
Notifies the receiver that the user has initiated a drag
over it. A drag is a mouse movement while the left button is down.
@@ -171,6 +180,15 @@ CPDownArrowKeyCode = 40;
[_nextResponder performSelector:_cmd withObject:anEvent];
}
/*!
Notifies the receiver that the user has released the right mouse button.
@param anEvent contains information about the release
*/
- (void)rightMouseUp:(CPEvent)anEvent
{
[_nextResponder performSelector:_cmd withObject:anEvent];
}
/*!
Notifies the receiver that the user has moved the mouse (with no buttons down).
@param anEvent contains information about the movement
+2 -3
View File
@@ -235,7 +235,7 @@ NAMES_FOR_PARTS[CPScrollerKnob] = @"knob";
*/
- (void)checkSpaceForParts
{
var bounds = [self bounds];
var bounds = [self bounds];
// Assume we won't be needing the arrows.
if (_knobProportion === 1.0)
@@ -290,8 +290,7 @@ NAMES_FOR_PARTS[CPScrollerKnob] = @"knob";
_partRects[CPScrollerDecrementLine] = _CGRectMakeZero();
_partRects[CPScrollerKnobSlot] = _CGRectMake(trackInset.left, 0, width - trackInset.left - trackInset.right, height);
}
}
}
else
{
var decrementLineSize = [self currentValueForThemeAttribute:"decrement-line-size"],
+56 -80
View File
@@ -24,26 +24,10 @@
#include "Platform/Platform.h"
/*!
@global
@group Menu tags
*/
CPSearchFieldRecentsTitleMenuItemTag = 1000;
/*!
@global
@group Menu tags
*/
CPSearchFieldRecentsMenuItemTag = 1001;
/*!
@global
@group Menu tags
*/
CPSearchFieldClearRecentsMenuItemTag = 1002;
/*!
@global
@group Menu tags
*/
CPSearchFieldNoRecentsMenuItemTag = 1003;
CPSearchFieldRecentsTitleMenuItemTag = 1000;
CPSearchFieldRecentsMenuItemTag = 1001;
CPSearchFieldClearRecentsMenuItemTag = 1002;
CPSearchFieldNoRecentsMenuItemTag = 1003;
var CPSearchFieldSearchImage = nil,
CPSearchFieldFindImage = nil,
@@ -79,64 +63,49 @@ var CPSearchFieldSearchImage = nil,
return;
var bundle = [CPBundle bundleForClass:self];
CPSearchFieldSearchImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldSearch.png"]];
CPSearchFieldFindImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldFind.png"]];
CPSearchFieldCancelImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldCancel.png"]];
CPSearchFieldCancelPressedImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldCancelPressed.png"]];
CPSearchFieldSearchImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldSearch.png"] size:CGSizeMake(25, 22)];
CPSearchFieldFindImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldFind.png"] size:CGSizeMake(25, 22)];
CPSearchFieldCancelImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldCancel.png"] size:CGSizeMake(22, 22)];
CPSearchFieldCancelPressedImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPSearchField/CPSearchFieldCancelPressed.png"] size:CGSizeMake(22, 22)];
}
- (id)initWithFrame:(CPRect)frame
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self != nil)
if (self = [super initWithFrame:frame])
{
_recentSearches = [CPArray array];
_maximumRecents = 10;
_sendsWholeSearchString = NO;
_sendsSearchStringImmediately = NO;
_recentsAutosaveName = nil;
[self setBezeled:YES];
[self setBezelStyle:CPTextFieldRoundedBezel];
[self setBordered:YES];
[self setEditable:YES];
[self setDelegate:self];
_cancelButton = [[CPButton alloc] initWithFrame:CPMakeRect(frame.size.width - 27,(frame.size.height-22)/2,22,22)];
[self resetCancelButton];
[_cancelButton setHidden:YES];
[_cancelButton setAutoresizingMask:CPViewMinXMargin];
[self addSubview:_cancelButton];
_searchButton = [[CPButton alloc] initWithFrame:CPMakeRect(5,(frame.size.height-25)/2,25,25)];
[self resetSearchButton];
[self addSubview:_searchButton];
[self _initWithFrame:frame];
#if PLATFORM(DOM)
_cancelButton._DOMElement.style.cursor = "default";
_searchButton._DOMElement.style.cursor = "default";
#endif
_cancelButton._DOMElement.style.cursor = "default";
_searchButton._DOMElement.style.cursor = "default";
#endif
}
return self;
}
- (id)copy
- (void)_initWithFrame:(CGRect)frame
{
var copy = [super copy];
[self setBezeled:YES];
[self setBezelStyle:CPTextFieldRoundedBezel];
[self setBordered:YES];
[self setEditable:YES];
[self setDelegate:self];
[copy setCancelButton:[_cancelButton copy]];
[copy setSearchButton:[_searchButton copy]];
[copy setSendsWholeSearchString:[_sendsWholeSearchString copy]];
[copy setSendsSearchStringImmediately:[_sendsSearchStringImmediately copy]];
[copy setMaximumRecents:_maximumRecents];
if (_recentsAutosaveName)
[copy setrecentsAutosaveName:[_recentsAutosaveName copy]];
if (_searchMenuTemplate)
[copy setSearchMenutemplate:[_searchMenuTemplate copy]];
_cancelButton = [[CPButton alloc] initWithFrame:CGRectMake(frame.size.width - 27,(frame.size.height-22)/2,22,22)];
[self resetCancelButton];
[_cancelButton setHidden:YES];
[_cancelButton setAutoresizingMask:CPViewMinXMargin];
[self addSubview:_cancelButton];
return copy;
_searchButton = [[CPButton alloc] initWithFrame:CGRectMake(5,(frame.size.height-25)/2,25,25)];
[self resetSearchButton];
[self addSubview:_searchButton];
}
// Managing Buttons
@@ -695,9 +664,7 @@ var CPSearchFieldSearchImage = nil,
@end
var CPSearchButtonKey = @"CPSearchButtonKey",
CPCancelButtonKey = @"CPCancelButtonKey",
CPRecentsAutosaveNameKey = @"CPRecentsAutosaveNameKey",
var CPRecentsAutosaveNameKey = @"CPRecentsAutosaveNameKey",
CPSendsWholeSearchStringKey = @"CPSendsWholeSearchStringKey",
CPSendsSearchStringImmediatelyKey = @"CPSendsSearchStringImmediatelyKey",
CPMaximumRecentsKey = @"CPMaximumRecentsKey",
@@ -707,13 +674,20 @@ var CPSearchButtonKey = @"CPSearchButtonKey",
- (void)encodeWithCoder:(CPCoder)coder
{
[super encodeWithCoder:coder];
[coder encodeObject:_searchButton forKey:CPSearchButtonKey];
[coder encodeObject:_cancelButton forKey:CPCancelButtonKey];
[_searchButton removeFromSuperview];
[_cancelButton removeFromSuperview];
[super encodeWithCoder:coder];
if (_searchButton)
[self addSubview:_searchButton];
if (_cancelButton)
[self addSubview:_cancelButton];
[coder encodeBool:_sendsWholeSearchString forKey:CPSendsWholeSearchStringKey];
[coder encodeBool:_sendsSearchStringImmediately forKey:CPSendsSearchStringImmediatelyKey];
[coder encodeInt:_maximumRecents forKey:CPMaximumRecentsKey];
if (_recentsAutosaveName)
[coder encodeObject:_recentsAutosaveName forKey:CPRecentsAutosaveNameKey];
if (_searchMenuTemplate)
@@ -722,21 +696,23 @@ var CPSearchButtonKey = @"CPSearchButtonKey",
- (id)initWithCoder:(CPCoder)coder
{
self = [super initWithCoder:coder];
_searchButton = [coder decodeObjectForKey:CPSearchButtonKey];
_cancelButton = [coder decodeObjectForKey:CPCancelButtonKey];
_recentsAutosaveName = [coder decodeObjectForKey:CPRecentsAutosaveNameKey];
_sendsWholeSearchString = [coder decodeBoolForKey:CPSendsWholeSearchStringKey];
_sendsSearchStringImmediately = [coder decodeBoolForKey:CPSendsSearchStringImmediatelyKey];
_maximumRecents = [coder decodeIntForKey:CPMaximumRecentsKey];
var template = [coder decodeObjectForKey:CPSearchMenuTemplateKey];
if (template)
[self setSearchMenuTemplate:template];
[self setDelegate:self];
if (self = [super initWithCoder:coder])
{
[self _initWithFrame:[self frame]];
_recentsAutosaveName = [coder decodeObjectForKey:CPRecentsAutosaveNameKey];
_sendsWholeSearchString = [coder decodeBoolForKey:CPSendsWholeSearchStringKey];
_sendsSearchStringImmediately = [coder decodeBoolForKey:CPSendsSearchStringImmediatelyKey];
_maximumRecents = [coder decodeIntForKey:CPMaximumRecentsKey];
var template = [coder decodeObjectForKey:CPSearchMenuTemplateKey];
if (template)
[self setSearchMenuTemplate:template];
[self setDelegate:self];
}
return self;
}
@end
@end
+193 -59
View File
@@ -20,6 +20,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import "CPButtonBar.j"
@import "CPImage.j"
@import "CPView.j"
@@ -43,18 +44,20 @@ var CPSplitViewHorizontalImage = nil,
id _delegate;
BOOL _isVertical;
BOOL _isPaneSplitter;
int _currentDivider;
float _initialOffset;
CPString _originComponent;
CPString _sizeComponent;
CPArray _DOMDividerElements;
CPString _dividerImagePath;
int _drawingDivider;
BOOL _needsResizeSubviews;
CPArray _buttonBars;
}
/*
@@ -77,10 +80,11 @@ var CPSplitViewHorizontalImage = nil,
_currentDivider = CPNotFound;
_DOMDividerElements = [];
_buttonBars = [];
[self _setVertical:YES];
}
return self;
}
@@ -98,7 +102,7 @@ var CPSplitViewHorizontalImage = nil,
{
if (![self _setVertical:shouldBeVertical])
return;
// Just re-adjust evenly.
var frame = [self frame],
dividerThickness = [self dividerThickness];
@@ -125,13 +129,13 @@ var CPSplitViewHorizontalImage = nil,
- (BOOL)_setVertical:(BOOL)shouldBeVertical
{
var changed = (_isVertical != shouldBeVertical);
_isVertical = shouldBeVertical;
_originComponent = [self isVertical] ? "x" : "y";
_sizeComponent = [self isVertical] ? "width" : "height";
_dividerImagePath = [self isVertical] ? [CPSplitViewVerticalImage filename] : [CPSplitViewHorizontalImage filename];
return changed;
}
@@ -150,7 +154,7 @@ var CPSplitViewHorizontalImage = nil,
if(_DOMDividerElements[_drawingDivider])
[self _setupDOMDivider]
// The divider changes size when pane splitter mode is toggled, so the
// The divider changes size when pane splitter mode is toggled, so the
// subviews need to change size too.
_needsResizeSubviews = YES;
[self setNeedsDisplay:YES];
@@ -209,18 +213,13 @@ var CPSplitViewHorizontalImage = nil,
{
_DOMDividerElements[_drawingDivider] = document.createElement("div");
if(_isVertical)
_DOMDividerElements[_drawingDivider].style.cursor = [[CPCursor resizeLeftRightCursor] _cssString];
else
_DOMDividerElements[_drawingDivider].style.cursor = [[CPCursor resizeUpDownCursor] _cssString];
_DOMDividerElements[_drawingDivider].style.position = "absolute";
_DOMDividerElements[_drawingDivider].style.backgroundRepeat = "repeat";
CPDOMDisplayServerAppendChild(_DOMElement, _DOMDividerElements[_drawingDivider]);
[self _setupDOMDivider];
}
}
CPDOMDisplayServerSetStyleLeftTop(_DOMDividerElements[_drawingDivider], NULL, _CGRectGetMinX(aRect), _CGRectGetMinY(aRect));
CPDOMDisplayServerSetStyleSize(_DOMDividerElements[_drawingDivider], _CGRectGetWidth(aRect), _CGRectGetHeight(aRect));
@@ -256,7 +255,7 @@ var CPSplitViewHorizontalImage = nil,
var subviews = [self subviews],
count = subviews.length,
oldSize = CGSizeMakeZero();
if ([self isVertical])
{
oldSize.width += [self dividerThickness] * (count - 1);
@@ -279,15 +278,25 @@ var CPSplitViewHorizontalImage = nil,
var frame = [_subviews[anIndex] frame],
startPosition = frame.origin[_originComponent] + frame.size[_sizeComponent],
effectiveRect = [self effectiveRectOfDividerAtIndex:anIndex],
buttonBar = _buttonBars[anIndex],
buttonBarRect = null,
additionalRect = null;
if (buttonBar != null)
{
buttonBarRect = [buttonBar resizeControlFrame];
buttonBarRect.origin = [self convertPoint:buttonBarRect.origin fromView:buttonBar];
}
if ([_delegate respondsToSelector:@selector(splitView:effectiveRect:forDrawnRect:ofDividerAtIndex:)])
effectiveRect = [_delegate splitView:self effectiveRect:effectiveRect forDrawnRect:effectiveRect ofDividerAtIndex:anIndex];
if ([_delegate respondsToSelector:@selector(splitView:additionalEffectiveRectOfDividerAtIndex:)])
additionalRect = [_delegate splitView:self additionalEffectiveRectOfDividerAtIndex:anIndex];
return CGRectContainsPoint(effectiveRect, aPoint) || (additionalRect && CGRectContainsPoint(additionalRect, aPoint));
return CGRectContainsPoint(effectiveRect, aPoint) ||
(additionalRect && CGRectContainsPoint(additionalRect, aPoint)) ||
(buttonBarRect && CGRectContainsPoint(buttonBarRect, aPoint));
}
- (CPView)hitTest:(CGPoint)aPoint
@@ -303,7 +312,7 @@ var CPSplitViewHorizontalImage = nil,
if ([self cursorAtPoint:point hitDividerAtIndex:i])
return self;
}
return [super hitTest:aPoint];
}
@@ -320,12 +329,13 @@ var CPSplitViewHorizontalImage = nil,
if (_currentDivider != CPNotFound)
{
_currentDivider = CPNotFound;
[self _updateResizeCursor:anEvent];
[self _postNotificationDidResize];
}
return;
}
if (type == CPLeftMouseDown)
{
var point = [self convertPoint:[anEvent locationInWindow] fromView:nil];
@@ -342,7 +352,7 @@ var CPSplitViewHorizontalImage = nil,
if ([anEvent clickCount] == 2 &&
[_delegate respondsToSelector:@selector(splitView:canCollapseSubview:)] &&
[_delegate respondsToSelector:@selector(splitView:shouldCollapseSubview:forDoubleClickOnDividerAtIndex:)])
{
{
var minPosition = [self minPossiblePositionOfDividerAtIndex:i],
maxPosition = [self maxPossiblePositionOfDividerAtIndex:i];
@@ -374,14 +384,16 @@ var CPSplitViewHorizontalImage = nil,
if (_currentDivider === CPNotFound)
return;
}
else if (type == CPLeftMouseDragged && _currentDivider != CPNotFound)
{
var point = [self convertPoint:[anEvent locationInWindow] fromView:nil];
[self setPosition:(point[_originComponent] + _initialOffset) ofDividerAtIndex:_currentDivider];
// Cursor might change if we reach a resize limit.
[self _updateResizeCursor:anEvent];
}
[CPApp setTarget:self selector:@selector(trackDivider:) forNextEventMatchingMask:CPLeftMouseDraggedMask | CPLeftMouseUpMask untilDate:nil inMode:nil dequeue:YES];
}
@@ -391,13 +403,81 @@ var CPSplitViewHorizontalImage = nil,
[self trackDivider:anEvent];
}
- (void)viewDidMoveToWindow
{
// Enable split view resize cursors. Commented out pending CPTrackingArea implementation.
//[[self window] setAcceptsMouseMovedEvents:YES];
}
- (void)mouseEntered:(CPEvent)anEvent
{
// Tracking code handles cursor by itself.
if (_currentDivider == CPNotFound)
[self _updateResizeCursor:anEvent];
}
- (void)mouseMoved:(CPEvent)anEvent
{
if (_currentDivider == CPNotFound)
[self _updateResizeCursor:anEvent];
}
- (void)mouseExited:(CPEvent)anEvent
{
if (_currentDivider == CPNotFound)
// FIXME: we should use CPCursor push/pop (if previous currentCursor != arrow).
[[CPCursor arrowCursor] set];
}
- (void)_updateResizeCursor:(CPEvent)anEvent
{
var point = [self convertPoint:[anEvent locationInWindow] fromView:nil];
if ([anEvent type] === CPLeftMouseUp && ![[self window] acceptsMouseMovedEvents])
{
[[CPCursor arrowCursor] set];
return;
}
for (var i = 0, count = [_subviews count] - 1; i < count; i++)
{
// If we are currently tracking, keep the resize cursor active even outside of hit areas.
if (_currentDivider === i || (_currentDivider == CPNotFound && [self cursorAtPoint:point hitDividerAtIndex:i]))
{
var frame = [_subviews[i] frame],
startPosition = frame.origin[_originComponent] + frame.size[_sizeComponent],
canShrink = [self _realPositionForPosition:startPosition-1 ofDividerAtIndex:i] < startPosition,
canGrow = [self _realPositionForPosition:startPosition+1 ofDividerAtIndex:i] > startPosition,
cursor = [CPCursor arrowCursor];
if (_isVertical && canShrink && canGrow)
cursor = [CPCursor resizeLeftRightCursor];
else if (_isVertical && canShrink)
cursor = [CPCursor resizeLeftCursor];
else if (_isVertical && canGrow)
cursor = [CPCursor resizeRightCursor];
else if (canShrink && canGrow)
cursor = [CPCursor resizeUpDownCursor];
else if (canShrink)
cursor = [CPCursor resizeUpCursor];
else if (canGrow)
cursor = [CPCursor resizeDownCursor];
[cursor set];
return;
}
}
[[CPCursor arrowCursor] set];
}
- (float)maxPossiblePositionOfDividerAtIndex:(int)dividerIndex
{
var frame = [_subviews[dividerIndex + 1] frame];
if (dividerIndex + 1 < [_subviews count] - 1)
return frame.origin[_originComponent] + frame.size[_sizeComponent] - [self dividerThickness];
else
else
return [self frame].size[_sizeComponent] - [self dividerThickness];
}
@@ -406,17 +486,15 @@ var CPSplitViewHorizontalImage = nil,
if (dividerIndex > 0)
{
var frame = [_subviews[dividerIndex - 1] frame];
return frame.origin[_originComponent] + frame.size[_sizeComponent] + [self dividerThickness];
}
else
else
return 0;
}
- (void)setPosition:(float)position ofDividerAtIndex:(int)dividerIndex
- (int)_realPositionForPosition:(float)position ofDividerAtIndex:(int)dividerIndex
{
[self _adjustSubviewsWithCalculatedSize];
// not sure where this should override other positions?
if ([_delegate respondsToSelector:@selector(splitView:constrainSplitPosition:ofSubviewAt:)])
position = [_delegate splitView:self constrainSplitPosition:position ofSubviewAt:dividerIndex];
@@ -425,47 +503,56 @@ var CPSplitViewHorizontalImage = nil,
proposedMin = [self minPossiblePositionOfDividerAtIndex:dividerIndex],
actualMax = proposedMax,
actualMin = proposedMin;
if([_delegate respondsToSelector:@selector(splitView:constrainMinCoordinate:ofSubviewAt:)])
actualMin = [_delegate splitView:self constrainMinCoordinate:proposedMin ofSubviewAt:dividerIndex];
if([_delegate respondsToSelector:@selector(splitView:constrainMaxCoordinate:ofSubviewAt:)])
actualMax = [_delegate splitView:self constrainMaxCoordinate:proposedMax ofSubviewAt:dividerIndex];
var frame = [self frame],
viewA = _subviews[dividerIndex],
frameA = [viewA frame],
viewB = _subviews[dividerIndex + 1],
frameB = [viewB frame];
var viewA = _subviews[dividerIndex],
realPosition = MAX(MIN(position, actualMax), actualMin);
var realPosition = MAX(MIN(position, actualMax), actualMin);
if (position < proposedMin + (actualMin - proposedMin) / 2)
if ([_delegate respondsToSelector:@selector(splitView:canCollapseSubview:)])
if ([_delegate splitView:self canCollapseSubview:viewA])
realPosition = proposedMin;
return realPosition;
}
- (void)setPosition:(float)position ofDividerAtIndex:(int)dividerIndex
{
[self _adjustSubviewsWithCalculatedSize];
var realPosition = [self _realPositionForPosition:position ofDividerAtIndex:dividerIndex];
var viewA = _subviews[dividerIndex],
frameA = [viewA frame],
viewB = _subviews[dividerIndex + 1],
frameB = [viewB frame];
frameA.size[_sizeComponent] = realPosition - frameA.origin[_originComponent];
[_subviews[dividerIndex] setFrame:frameA];
frameB.size[_sizeComponent] = frameB.origin[_originComponent] + frameB.size[_sizeComponent] - realPosition - [self dividerThickness];
frameB.origin[_originComponent] = realPosition + [self dividerThickness];
[_subviews[dividerIndex + 1] setFrame:frameB];
[self setNeedsDisplay:YES];
}
- (void)setFrameSize:(CGSize)aSize
{
[self _adjustSubviewsWithCalculatedSize];
[super setFrameSize:aSize];
[self setNeedsDisplay:YES];
}
- (void)resizeSubviewsWithOldSize:(CPSize)oldSize
{
{
if ([_delegate respondsToSelector:@selector(splitView:resizeSubviewsWithOldSize:)])
{
[_delegate splitView:self resizeSubviewsWithOldSize:oldSize];
@@ -473,7 +560,7 @@ var CPSplitViewHorizontalImage = nil,
}
[self _postNotificationWillResize];
var index = 0,
count = [_subviews count],
bounds = [self bounds],
@@ -524,7 +611,7 @@ var CPSplitViewHorizontalImage = nil,
else if (totalSizableSpace && !isSizable)
viewFrame.size[_sizeComponent] = [view frame].size[_sizeComponent];
bounds.origin[_originComponent] += viewFrame.size[_sizeComponent] + dividerThickness;
bounds.origin[_originComponent] += viewFrame.size[_sizeComponent] + dividerThickness;
[view setFrame:viewFrame];
}
@@ -538,7 +625,7 @@ var CPSplitViewHorizontalImage = nil,
[[CPNotificationCenter defaultCenter] removeObserver:_delegate name:CPSplitViewDidResizeSubviewsNotification object:self];
if ([_delegate respondsToSelector:@selector(splitViewWillResizeSubviews:)])
[[CPNotificationCenter defaultCenter] removeObserver:_delegate name:CPSplitViewWillResizeSubviewsNotification object:self];
_delegate = delegate;
if ([_delegate respondsToSelector:@selector(splitViewDidResizeSubviews:)])
@@ -553,6 +640,47 @@ var CPSplitViewHorizontalImage = nil,
object:self];
}
/*!
Set the button bar who's resize control should act as a control for this splitview.
Each divider can have at most one button bar assigned to it, and that button bar must be
a subview of one of the split view's subviews.
Calling this method with nil as the button bar will remove any currently assigned button bar
for the divider at that index. Indexes will not be adjusted as new subviews are added, so you
should usually call this method after adding all the desired subviews to the split view.
This method will automatically configure the hasResizeControl and resizeControlIsLeftAligned
parameters of the button bar, and will override any currently set values.
*/
- (void)setButtonBar:(CPButtonBar)aButtonBar forDividerAtIndex:(unsigned)dividerIndex
{
if (!aButtonBar)
{
_buttonBars[dividerIndex] = nil;
return;
}
var view = [aButtonBar superview],
subview = aButtonBar;
while (view && view !== self)
{
subview = view;
view = [view superview];
}
if (view !== self)
[CPException raise:CPInvalidArgumentException
reason:@"CPSplitView button bar must be a subview of the split view."];
var viewIndex = [[self subviews] indexOfObject:subview];
[aButtonBar setHasResizeControl:YES];
[aButtonBar setResizeControlIsLeftAligned:dividerIndex < viewIndex];
_buttonBars[dividerIndex] = aButtonBar;
}
- (void)_postNotificationWillResize
{
[[CPNotificationCenter defaultCenter] postNotificationName:CPSplitViewWillResizeSubviewsNotification object:self];
@@ -567,7 +695,8 @@ var CPSplitViewHorizontalImage = nil,
var CPSplitViewDelegateKey = "CPSplitViewDelegateKey",
CPSplitViewIsVerticalKey = "CPSplitViewIsVerticalKey",
CPSplitViewIsPaneSplitterKey = "CPSplitViewIsPaneSplitterKey";
CPSplitViewIsPaneSplitterKey = "CPSplitViewIsPaneSplitterKey",
CPSplitViewButtonBarsKey = "CPSplitViewButtonBarsKey";
@implementation CPSplitView (CPCoding)
@@ -578,19 +707,21 @@ var CPSplitViewDelegateKey = "CPSplitViewDelegateKey",
- (id)initWithCoder:(CPCoder)aCoder
{
self = [super initWithCoder:aCoder];
if (self)
{
_currentDivider = CPNotFound;
_DOMDividerElements = [];
_buttonBars = [aCoder decodeObjectForKey:CPSplitViewButtonBarsKey] || [];
_delegate = [aCoder decodeObjectForKey:CPSplitViewDelegateKey];;
_delegate = [aCoder decodeObjectForKey:CPSplitViewDelegateKey];
_isPaneSplitter = [aCoder decodeBoolForKey:CPSplitViewIsPaneSplitterKey];
[self _setVertical:[aCoder decodeBoolForKey:CPSplitViewIsVerticalKey]];
}
return self;
}
@@ -601,9 +732,12 @@ var CPSplitViewDelegateKey = "CPSplitViewDelegateKey",
- (void)encodeWithCoder:(CPCoder)aCoder
{
[super encodeWithCoder:aCoder];
//FIXME how should we handle this?
//[aCoder encodeObject:_buttonBars forKey:CPSplitViewButtonBarsKey];
[aCoder encodeConditionalObject:_delegate forKey:CPSplitViewDelegateKey];
[aCoder encodeBool:_isVertical forKey:CPSplitViewIsVerticalKey];
[aCoder encodeBool:_isPaneSplitter forKey:CPSplitViewIsPaneSplitterKey];
}
+2 -2
View File
@@ -81,8 +81,8 @@ CPTableColumnUserResizingMask = 1 << 1;
var textDataView = [CPTextField new];
[textDataView setLineBreakMode:CPLineBreakByTruncatingTail];
[textDataView setValue:[CPColor colorWithHexString:@"333333"] forThemeAttribute:@"text-color"];
[textDataView setValue:[CPColor whiteColor] forThemeAttribute:@"text-color" inState:CPThemeStateHighlighted];
[textDataView setValue:[CPFont boldSystemFontOfSize:12] forThemeAttribute:@"font" inState:CPThemeStateHighlighted];
[textDataView setValue:[CPColor whiteColor] forThemeAttribute:@"text-color" inState:CPThemeStateSelected];
[textDataView setValue:[CPFont boldSystemFontOfSize:12] forThemeAttribute:@"font" inState:CPThemeStateSelected];
[textDataView setValue:CPCenterVerticalTextAlignment forThemeAttribute:@"vertical-alignment"];
[self setDataView:textDataView];
}
+20 -24
View File
@@ -24,8 +24,6 @@
@import "CPTableView.j"
@import "CPView.j"
var CPThemeStatePressed = CPThemeState("pressed");
@implementation _CPTableColumnHeaderView : CPView
{
_CPImageAndTextView _textField;
@@ -62,11 +60,11 @@ var CPThemeStatePressed = CPThemeState("pressed");
{
var themeState = [self themeState];
if(themeState & CPThemeStateHighlighted && themeState & CPThemeStatePressed)
if(themeState & CPThemeStateSelected && themeState & CPThemeStateHighlighted)
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview-highlighted-pressed.png", CGSizeMake(1.0, 22.0))]];
else if (themeState & CPThemeStateHighlighted)
else if (themeState & CPThemeStateSelected)
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview-highlighted.png", CGSizeMake(1.0, 22.0))]];
else if (themeState & CPThemeStatePressed)
else if (themeState & CPThemeStateHighlighted)
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview-pressed.png", CGSizeMake(1.0, 22.0))]];
else
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview.png", CGSizeMake(1.0, 22.0))]];
@@ -160,21 +158,24 @@ var _CPTableColumnHeaderViewStringValueKey = @"_CPTableColumnHeaderViewStringVal
CPTableView _tableView @accessors(property=tableView);
}
- (void)initWithFrame:(CGRect)aFrame
- (void)_init
{
_resizedColumn = -1;
_draggedColumn = -1;
_pressedColumn = -1;
_draggedDistance = 0.0;
_lastLocation = nil;
_columnOldWidth = nil;
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview.png", CGSizeMake(1.0, 22.0))]];
}
- (id)initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self)
{
_resizedColumn = -1;
_draggedColumn = -1;
_pressedColumn = -1;
_draggedDistance = 0.0;
_lastLocation = nil;
_columnOldWidth = nil;
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview.png", CGSizeMake(1.0, 22.0))]];
}
[self _init];
return self;
}
@@ -221,13 +222,13 @@ var _CPTableColumnHeaderViewStringValueKey = @"_CPTableColumnHeaderViewStringVal
if (_pressedColumn != -1)
{
var headerView = [_tableView._tableColumns[_pressedColumn] headerView];
[headerView unsetThemeState:CPThemeStatePressed];
[headerView unsetThemeState:CPThemeStateHighlighted];
}
if (column != -1)
{
var headerView = [_tableView._tableColumns[column] headerView];
[headerView setThemeState:CPThemeStatePressed];
[headerView setThemeState:CPThemeStateHighlighted];
}
_pressedColumn = column;
@@ -481,12 +482,7 @@ var CPTableHeaderViewTableViewKey = @"CPTableHeaderViewTableViewKey";
{
if (self = [super initWithCoder:aCoder])
{
_resizedColumn = -1;
_draggedColumn = -1;
_pressedColumn = -1;
_draggedDistance = 0.0;
_lastLocation = nil;
_columnOldWidth = nil;
[self _init];
_tableView = [aCoder decodeObjectForKey:CPTableHeaderViewTableViewKey];
}
+74 -79
View File
@@ -67,29 +67,29 @@ var CPTableViewDelegate_selectionShouldChangeInTableView_
CPTableViewDelegate_tableViewSelectionIsChanging_ = 1 << 19;
//CPTableViewDraggingDestinationFeedbackStyles
CPTableViewDraggingDestinationFeedbackStyleNone = -1,
CPTableViewDraggingDestinationFeedbackStyleRegular = 0,
CPTableViewDraggingDestinationFeedbackStyleNone = -1;
CPTableViewDraggingDestinationFeedbackStyleRegular = 0;
CPTableViewDraggingDestinationFeedbackStyleSourceList = 1;
//CPTableViewDropOperations
CPTableViewDropOn = 0,
CPTableViewDropOn = 0;
CPTableViewDropAbove = 1;
// TODO: add docs
CPTableViewSelectionHighlightStyleNone = -1,
CPTableViewSelectionHighlightStyleRegular = 0,
CPTableViewSelectionHighlightStyleNone = -1;
CPTableViewSelectionHighlightStyleRegular = 0;
CPTableViewSelectionHighlightStyleSourceList = 1;
CPTableViewGridNone = 0;
CPTableViewSolidVerticalGridLineMask = 1 << 0;
CPTableViewSolidHorizontalGridLineMask = 1 << 1;
CPTableViewNoColumnAutoresizing = 0,
CPTableViewUniformColumnAutoresizingStyle = 1,
CPTableViewSequentialColumnAutoresizingStyle = 2,
CPTableViewReverseSequentialColumnAutoresizingStyle = 3,
CPTableViewLastColumnOnlyAutoresizingStyle = 4,
CPTableViewNoColumnAutoresizing = 0;
CPTableViewUniformColumnAutoresizingStyle = 1;
CPTableViewSequentialColumnAutoresizingStyle = 2;
CPTableViewReverseSequentialColumnAutoresizingStyle = 3;
CPTableViewLastColumnOnlyAutoresizingStyle = 4;
CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
@@ -194,15 +194,17 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
SEL _doubleAction;
unsigned _columnAutoResizingStyle;
int _lastTrackedRowIndex;
CGPoint _originalMouseDownPoint;
BOOL _verticalMotionCanDrag;
unsigned _destinationDragStyle;
BOOL _isSelectingSession;
CPIndexSet _draggedRowIndexes;
_dropOperationDrawingView _dropOperationFeedbackView;
CPDragOperation _dragOperationDefaultMask;
int _retargetedDropRow;
CPDragOperation _retargetedDropOperation;
_CPDropOperationDrawingView _dropOperationFeedbackView;
CPDragOperation _dragOperationDefaultMask;
int _retargetedDropRow;
CPDragOperation _retargetedDropOperation;
BOOL _disableAutomaticResizing @accessors(property=disableAutomaticResizing);
BOOL _lastColumnShouldSnap;
@@ -261,14 +263,14 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
[_headerView setTableView:self];
_cornerView = [[_CPCornerView alloc] initWithFrame:CGRectMake(0, 0, [CPScroller scrollerWidth], CGRectGetHeight([_headerView frame]))];
_lastSelectedRow = -1;
_selectedColumnIndexes = [CPIndexSet indexSet];
_selectedRowIndexes = [CPIndexSet indexSet];
_currentHighlightedTableColumn = nil;
_sortDescriptors = [CPArray array];
_draggedRowIndexes = [CPIndexSet indexSet];
_verticalMotionCanDrag = YES;
_isSelectingSession = NO;
@@ -276,10 +278,6 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
_retargetedDropOperation = nil;
_dragOperationDefaultMask = nil;
_destinationDragStyle = CPTableViewDraggingDestinationFeedbackStyleRegular;
_dropOperationFeedbackView = [[_dropOperationDrawingView alloc] initWithFrame:_CGRectMakeZero()];
[self addSubview:_dropOperationFeedbackView];
[_dropOperationFeedbackView setHidden:YES];
[_dropOperationFeedbackView setTableView:self];
_tableDrawView = [[_CPTableDrawView alloc] initWithTableView:self];
[_tableDrawView setBackgroundColor:[CPColor clearColor]];
@@ -294,6 +292,9 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
// FIX ME: we have a lot of redundent init stuff in initWithFrame: and initWithCoder: we should move it all into here.
- (void)_init
{
_dropOperationFeedbackView = [[_CPDropOperationDrawingView alloc] initWithFrame:_CGRectMakeZero()];
[_dropOperationFeedbackView setTableView:self];
_lastColumnShouldSnap = NO;
_backgroundColor = [CPColor whiteColor];
@@ -807,7 +808,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
var rowIndex = deselectRows[count];
var view = dataViewsInTableColumn[rowIndex];
[view unsetThemeState:CPThemeStateHighlighted];
[view unsetThemeState:CPThemeStateSelected];
}
count = selectRows.length;
@@ -815,7 +816,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
var rowIndex = selectRows[count];
var view = dataViewsInTableColumn[rowIndex];
[view setThemeState:CPThemeStateHighlighted];
[view setThemeState:CPThemeStateSelected];
}
}
}
@@ -847,13 +848,13 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
var rowIndex = selectRows[i],
dataView = dataViewsInTableColumn[rowIndex];
[dataView unsetThemeState:CPThemeStateHighlighted];
[dataView unsetThemeState:CPThemeStateSelected];
}
if (_headerView)
{
var headerView = [_tableColumns[columnIndex] headerView];
[headerView unsetThemeState:CPThemeStateHighlighted];
[headerView unsetThemeState:CPThemeStateSelected];
}
}
@@ -868,16 +869,21 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
var rowIndex = selectRows[i],
dataView = dataViewsInTableColumn[rowIndex];
[dataView setThemeState:CPThemeStateHighlighted];
[dataView setThemeState:CPThemeStateSelected];
}
if (_headerView)
{
var headerView = [_tableColumns[columnIndex] headerView];
[headerView setThemeState:CPThemeStateHighlighted];
[headerView setThemeState:CPThemeStateSelected];
}
}
}
- (int)selectedColumn
{
[_selectedColumnIndexes lastIndex];
}
- (CPIndexSet)selectedColumnIndexes
{
return _selectedColumnIndexes;
@@ -1738,10 +1744,10 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
if (_headerView)
{
if (_currentHighlightedTableColumn != nil)
[[_currentHighlightedTableColumn headerView] unsetThemeState:CPThemeStateHighlighted];
[[_currentHighlightedTableColumn headerView] unsetThemeState:CPThemeStateSelected];
if (aTableColumn != nil)
[[aTableColumn headerView] setThemeState:CPThemeStateHighlighted];
[[aTableColumn headerView] setThemeState:CPThemeStateSelected];
}
_currentHighlightedTableColumn = aTableColumn;
@@ -1757,63 +1763,44 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
return YES;
}
- (CPImage)dragImageForRowsWithIndexes:(CPIndexSet)dragRows
tableColumns:(CPArray)theTableColumns
event:(CPEvent)dragEvent
offset:(CPPointPointer)dragImageOffset
- (CPImage)dragImageForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CPPointPointer)dragImageOffset
{
return [[CPImage alloc] initWithContentsOfFile:@"Frameworks/AppKit/Resources/GenericFile.png" size:CGSizeMake(32,32)];
}
- (CPView)dragViewForRowsWithIndexes:(CPIndexSet)theDraggedRows
tableColumns:(CPArray)theTableColumns
event:(CPEvent)theDragEvent
offset:(CPPoint)dragViewOffset
- (CPView)dragViewForRowsWithIndexes:(CPIndexSet)theDraggedRows tableColumns:(CPArray)theTableColumns event:(CPEvent)theDragEvent offset:(CPPoint)dragViewOffset
{
var bounds = [self bounds],
view = [[CPView alloc] initWithFrame:bounds];
[view setBackgroundColor:[CPColor clearColor]];
[view setAlphaValue:0.7];
// We have to fetch all the data views for the selected rows and columns
// After that we can copy these add them to a transparent drag view and use that drag view
// to make it appear we are dragging images of those rows (as you would do in regular Cocoa)
var firstExposedColumn = [_exposedColumns firstIndex],
firstExposedRow = [_exposedRows firstIndex],
exposedColumnsLength = [_exposedColumns lastIndex] - firstExposedColumn + 1,
exposedRowsLength = [_exposedRows lastIndex] - firstExposedRow + 1,
columns = [],
rows = [];
[_exposedColumns getIndexes:columns maxCount:-1 inIndexRange:CPMakeRange(firstExposedColumn, exposedColumnsLength)];
[theDraggedRows getIndexes:rows maxCount:-1 inIndexRange:CPMakeRange(firstExposedRow, exposedRowsLength)];
var columnIndex = [columns count];
var columnIndex = [theTableColumns count];
while (columnIndex--)
{
var column = columns[columnIndex],
tableColumn = [_tableColumns objectAtIndex:column],
rowIndex = [rows count];
while (rowIndex--)
var tableColumn = [theTableColumns objectAtIndex:columnIndex],
row = [theDraggedRows firstIndex];
while (row !== CPNotFound)
{
var row = rows[rowIndex];
var dataView = [self _newDataViewForRow:row tableColumn:tableColumn];
[dataView setBackgroundColor:[CPColor clearColor]];
[dataView setFrame:[self frameOfDataViewAtColumn:column row:row]];
[dataView setFrame:[self frameOfDataViewAtColumn:columnIndex row:row]];
[dataView setObjectValue:[self _objectValueForTableColumn:tableColumn row:row]];
[view addSubview:dataView];
row = [theDraggedRows indexGreaterThanIndex:row];
}
}
var dragPoint = [self convertPoint:[theDragEvent locationInWindow] fromView:nil];
dragViewOffset.x = CGRectGetWidth(bounds)/2 - dragPoint.x;
dragViewOffset.y = CGRectGetHeight(bounds)/2 - dragPoint.y;
return view;
}
@@ -1835,7 +1822,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
var numberOfRows = [self numberOfRows] + 1;
var reason = @"Attempt to set dropRow=" + row +
" dropOperation=CPTableViewDropOn when [0 - " + numberOfRows + "] is valid range of rows."
[[CPException exceptionWithName:@"Error" reason:reason userInfo:nil] raise];
}
@@ -1891,7 +1878,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
return;
_sortDescriptors = newSortDescriptors;
[self _sendDataSourceSortDescriptorsDidChange:oldSortDescriptors];
}
@@ -1991,7 +1978,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
// Now clear all the leftovers
// FIXME: this could be faster!
for (identifier in _cachedDataViews)
for (var identifier in _cachedDataViews)
{
var dataViews = _cachedDataViews[identifier],
count = dataViews.length;
@@ -2078,9 +2065,9 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
[dataView setObjectValue:[self _objectValueForTableColumn:tableColumn row:row]];
if (isColumnSelected || [self isRowSelected:row])
[dataView setThemeState:CPThemeStateHighlighted];
[dataView setThemeState:CPThemeStateSelected];
else
[dataView unsetThemeState:CPThemeStateHighlighted];
[dataView unsetThemeState:CPThemeStateSelected];
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_willDisplayView_forTableColumn_row_)
[_delegate tableView:self willDisplayView:dataView forTableColumn:tableColumn row:row];
@@ -2149,12 +2136,12 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
}
}
- (void)_commitDataViewObjectValue:(CPTextView)sender
- (void)_commitDataViewObjectValue:(id)sender
{
[_dataSource tableView:self
setObjectValue:[sender objectValue]
forTableColumn:sender.tableViewEditedColumnObj
row:sender.tableViewEditedRowIndex];
[_dataSource tableView:self setObjectValue:[sender objectValue] forTableColumn:sender.tableViewEditedColumnObj row:sender.tableViewEditedRowIndex];
if ([sender respondsToSelector:@selector(setEditable:)])
[sender setEditable:NO];
}
- (CPView)_newDataViewForRow:(CPInteger)aRow tableColumn:(CPTableColumn)aTableColumn
@@ -2649,8 +2636,11 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
}
_isSelectingSession = YES;
if(row >= 0)
if(row >= 0 && row !== _lastTrackedRowIndex)
{
_lastTrackedRowIndex = row;
[self _updateSelectionWithMouseAtRow:row];
}
if ((_implementedDataSourceMethods & CPTableViewDataSource_tableView_setObjectValue_forTableColumn_row_)
&& !_trackingPointMovedOutOfClickSlop)
@@ -2760,7 +2750,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
*/
- (void)draggingExited:(id)sender
{
[_dropOperationFeedbackView setHidden:YES];
[_dropOperationFeedbackView removeFromSuperview];
}
/*
@@ -2776,7 +2766,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
_retargetedDropOperation = nil;
_retargetedDropRow = nil;
_draggedRowIndexes = [CPIndexSet indexSet];
[_dropOperationFeedbackView setHidden:YES];
[_dropOperationFeedbackView removeFromSuperview];
}
/*
@ignore
@@ -2909,7 +2899,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
// FIX ME: is there anything else that needs to happen here?
// actual validation is called in dragginUpdated:
[_dropOperationFeedbackView setHidden:YES];
[_dropOperationFeedbackView removeFromSuperview];
return (_implementedDataSourceMethods & CPTableViewDataSource_tableView_validateDrop_proposedRow_proposedDropOperation_);
}
@@ -3185,6 +3175,7 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
CPTableViewGridColorKey = @"CPTableViewGridColorKey",
CPTableViewGridStyleMaskKey = @"CPTableViewGridStyleMaskKey",
CPTableViewUsesAlternatingBackgroundKey = @"CPTableViewUsesAlternatingBackgroundKey",
CPTableViewAlternatingRowColorsKey = @"CPTableViewAlternatingRowColorsKey",
CPTableViewHeaderViewKey = @"CPTableViewHeaderViewKey",
CPTableViewCornerViewKey = @"CPTableViewCornerViewKey";
@@ -3234,6 +3225,9 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
_gridColor = [aCoder decodeObjectForKey:CPTableViewGridColorKey] || [CPColor grayColor];
_gridStyleMask = [aCoder decodeIntForKey:CPTableViewGridStyleMaskKey] || CPTableViewGridNone;
_alternatingRowBackgroundColors = [aCoder decodeObjectForKey:CPTableViewAlternatingRowColorsKey];
_usesAlternatingRowBackgroundColors = [aCoder decodeObjectForKey:CPTableViewUsesAlternatingBackgroundKey]
_headerView = [aCoder decodeObjectForKey:CPTableViewHeaderViewKey];
_cornerView = [aCoder decodeObjectForKey:CPTableViewCornerViewKey];
@@ -3277,6 +3271,7 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
[aCoder encodeInt:_gridStyleMask forKey:CPTableViewGridStyleMaskKey];
[aCoder encodeBool:_usesAlternatingRowBackgroundColors forKey:CPTableViewUsesAlternatingBackgroundKey];
[aCoder encodeObject:_alternatingRowBackgroundColors forKey:CPTableViewAlternatingRowColorsKey]
[aCoder encodeObject:_cornerView forKey:CPTableViewCornerViewKey];
[aCoder encodeObject:_headerView forKey:CPTableViewHeaderViewKey];
@@ -3321,7 +3316,7 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
@end
@implementation _dropOperationDrawingView : CPView
@implementation _CPDropOperationDrawingView : CPView
{
unsigned dropOperation @accessors;
CPTableView tableView @accessors;
+3 -3
View File
@@ -813,7 +813,7 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if (![CPPlatform isBrowser])
{
[self copy:sender];
[self deleteBackwards:sender];
[self deleteBackward:sender];
}
}
@@ -826,7 +826,7 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if (![[pasteboard types] containsObject:CPStringPboardType])
return;
[self deleteBackwards:sender];
[self deleteBackward:sender];
var selectedRange = [self selectedRange],
stringValue = [self stringValue],
@@ -912,7 +912,7 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
[self selectText:sender];
}
- (void)deleteBackwards:(id)sender
- (void)deleteBackward:(id)sender
{
var selectedRange = [self selectedRange],
stringValue = [self stringValue],
+71 -26
View File
@@ -243,6 +243,11 @@ var CPViewFlags = { },
return [CPSet setWithObjects:@"boundsOrigin", @"boundsSize"];
}
+ (CPMenu)defaultMenu
{
return nil;
}
- (id)init
{
return [self initWithFrame:CGRectMakeZero()];
@@ -668,7 +673,7 @@ var CPViewFlags = { },
return _tag;
}
- (void)viewWithTag:(CPInteger)aTag
- (CPView)viewWithTag:(CPInteger)aTag
{
if ([self tag] == aTag)
return self;
@@ -1199,7 +1204,7 @@ var CPViewFlags = { },
if (CPFeatureIsCompatible(CPOpacityRequiresFilterFeature))
{
if (anAlphaValue == 1.0)
if (anAlphaValue === 1.0)
try { _DOMElement.style.removeAttribute("filter") } catch (anException) { }
else
_DOMElement.style.filter = "alpha(opacity=" + anAlphaValue * 100 + ")";
@@ -1309,6 +1314,22 @@ var CPViewFlags = { },
[super mouseDown:anEvent];
}
- (void)rightMouseDown:(CPEvent)anEvent
{
var menu = [self menuForEvent:anEvent];
if (menu)
[CPMenu popUpContextMenu:menu withEvent:anEvent forView:self];
else if ([[self nextResponder] isKindOfClass:CPView])
[super rightMouseDown:anEvent];
else
[[[anEvent window] platformWindow] _propagateContextMenuDOMEvent:YES];
}
- (CPMenu)menuForEvent:(CPEvent)anEvent
{
return [self menu] || [[self class] defaultMenu];
}
/*!
Sets the background color of the receiver.
@param aColor the new color for the receiver's background
@@ -1317,56 +1338,72 @@ var CPViewFlags = { },
{
if (_backgroundColor == aColor)
return;
_backgroundColor = aColor;
#if PLATFORM(DOM)
var patternImage = [_backgroundColor patternImage],
colorExists = _backgroundColor && ([_backgroundColor patternImage] || [_backgroundColor alphaComponent] > 0.0),
colorHasAlpha = colorExists && [_backgroundColor alphaComponent] < 1.0,
supportsRGBA = CPFeatureIsCompatible(CPCSSRGBAFeature),
colorNeedsDOMElement = colorHasAlpha && !supportsRGBA,
amount = 0;
if ([patternImage isThreePartImage])
{
_backgroundType = [patternImage isVertical] ? BackgroundVerticalThreePartImage : BackgroundHorizontalThreePartImage;
amount = 3 - _DOMImageParts.length;
}
else if ([patternImage isNinePartImage])
{
_backgroundType = BackgroundNinePartImage;
amount = 9 - _DOMImageParts.length;
amount = 9 - _DOMImageParts.length;
}
else
{
_backgroundType = BackgroundTrivialColor;
amount = 0 - _DOMImageParts.length;
amount = (colorNeedsDOMElement ? 1 : 0) - _DOMImageParts.length;
}
if (amount > 0)
{
while (amount--)
{
var DOMElement = DOMElementPrototype.cloneNode(false);
DOMElement.style.zIndex = -1000;
_DOMImageParts.push(DOMElement);
_DOMElement.appendChild(DOMElement);
}
}
else
{
amount = -amount;
while (amount--)
_DOMElement.removeChild(_DOMImageParts.pop());
}
if (_backgroundType == BackgroundTrivialColor)
// Opera doesn't like DOM properties set to nil.
// https://trac.280north.com/ticket/7
_DOMElement.style.background = _backgroundColor ? [_backgroundColor cssString] : "";
if (_backgroundType === BackgroundTrivialColor)
{
var colorCSS = colorExists ? [_backgroundColor cssString] : "";
if (colorNeedsDOMElement)
{
_DOMElement.style.background = "";
_DOMImageParts[0].style.background = [_backgroundColor cssString];
if (CPFeatureIsCompatible(CPOpacityRequiresFilterFeature))
_DOMImageParts[0].style.filter = "alpha(opacity=" + [_backgroundColor alphaComponent] * 100 + ")";
else
_DOMImageParts[0].style.opacity = [_backgroundColor alphaComponent];
var size = [self bounds].size;
CPDOMDisplayServerSetStyleSize(_DOMImageParts[0], size.width, size.height);
}
else
_DOMElement.style.background = colorCSS;
}
else
{
var slices = [patternImage imageSlices],
@@ -1377,23 +1414,31 @@ var CPViewFlags = { },
{
var image = slices[count],
size = _DOMImageSizes[count] = image ? [image size] : _CGSizeMakeZero();
CPDOMDisplayServerSetStyleSize(_DOMImageParts[count], size.width, size.height);
_DOMImageParts[count].style.background = image ? "url(\"" + [image filename] + "\")" : "";
if (!supportsRGBA)
{
if (CPFeatureIsCompatible(CPOpacityRequiresFilterFeature))
try { _DOMImageParts[count].style.removeAttribute("filter") } catch (anException) { }
else
_DOMImageParts[count].style.opacity = 1.0;
}
}
if (_backgroundType == BackgroundNinePartImage)
{
var width = frameSize.width - _DOMImageSizes[0].width - _DOMImageSizes[2].width,
height = frameSize.height - _DOMImageSizes[0].height - _DOMImageSizes[6].height;
CPDOMDisplayServerSetStyleSize(_DOMImageParts[1], width, _DOMImageSizes[0].height);
CPDOMDisplayServerSetStyleSize(_DOMImageParts[3], _DOMImageSizes[3].width, height);
CPDOMDisplayServerSetStyleSize(_DOMImageParts[4], width, height);
CPDOMDisplayServerSetStyleSize(_DOMImageParts[5], _DOMImageSizes[5].width, height);
CPDOMDisplayServerSetStyleSize(_DOMImageParts[7], width, _DOMImageSizes[7].height);
CPDOMDisplayServerSetStyleLeftTop(_DOMImageParts[0], NULL, 0.0, 0.0);
CPDOMDisplayServerSetStyleLeftTop(_DOMImageParts[1], NULL, _DOMImageSizes[0].width, 0.0);
CPDOMDisplayServerSetStyleRightTop(_DOMImageParts[2], NULL, 0.0, 0.0);
@@ -1407,7 +1452,7 @@ var CPViewFlags = { },
else if (_backgroundType == BackgroundVerticalThreePartImage)
{
CPDOMDisplayServerSetStyleSize(_DOMImageParts[1], frameSize.width, frameSize.height - _DOMImageSizes[0].height - _DOMImageSizes[2].height);
CPDOMDisplayServerSetStyleLeftTop(_DOMImageParts[0], NULL, 0.0, 0.0);
CPDOMDisplayServerSetStyleLeftTop(_DOMImageParts[1], NULL, 0.0, _DOMImageSizes[0].height);
CPDOMDisplayServerSetStyleLeftBottom(_DOMImageParts[2], NULL, 0.0, 0.0);
@@ -1415,7 +1460,7 @@ var CPViewFlags = { },
else if (_backgroundType == BackgroundHorizontalThreePartImage)
{
CPDOMDisplayServerSetStyleSize(_DOMImageParts[1], frameSize.width - _DOMImageSizes[0].width - _DOMImageSizes[2].width, frameSize.height);
CPDOMDisplayServerSetStyleLeftTop(_DOMImageParts[0], NULL, 0.0, 0.0);
CPDOMDisplayServerSetStyleLeftTop(_DOMImageParts[1], NULL, _DOMImageSizes[0].width, 0.0);
CPDOMDisplayServerSetStyleRightTop(_DOMImageParts[2], NULL, 0.0, 0.0);
+55 -27
View File
@@ -472,9 +472,6 @@ CPTexturedBackgroundWindowMask
- (void)awakeFromCib
{
if (_initialFirstResponder)
[self makeFirstResponder:_initialFirstResponder];
_keyViewLoopIsDirty = ![self _hasKeyViewLoop];
}
@@ -738,6 +735,15 @@ CPTexturedBackgroundWindowMask
{
[_platformWindow orderFront:self];
[_platformWindow order:CPWindowAbove window:self relativeTo:nil];
if (_firstResponder === self || !_firstResponder)
[self makeFirstResponder:[self initialFirstResponder]];
if (!CPApp._keyWindow)
[self makeKeyWindow];
if (!CPApp._mainWindow)
[self makeMainWindow];
}
/*
@@ -1161,6 +1167,16 @@ CPTexturedBackgroundWindowMask
return YES;
}
- (id)initialFirstResponder
{
return _initialFirstResponder;
}
- (void)setInitialFirstResponder:(id)aResponder
{
_initialFirstResponder = aResponder;
}
/*!
Attempts to make the \c aResponder the first responder. Before trying
to make it the first responder, the receiver will ask the current first responder
@@ -1170,7 +1186,7 @@ CPTexturedBackgroundWindowMask
*/
- (BOOL)makeFirstResponder:(CPResponder)aResponder
{
if (_firstResponder == aResponder)
if (_firstResponder === aResponder)
return YES;
if(![_firstResponder resignFirstResponder])
@@ -1331,44 +1347,58 @@ CPTexturedBackgroundWindowMask
case CPScrollWheel: return [[_windowView hitTest:point] scrollWheel:anEvent];
case CPLeftMouseUp: if (!_leftMouseDownView)
return [[_windowView hitTest:point] mouseUp:anEvent];
case CPLeftMouseUp:
case CPRightMouseUp: var hitTestedView = _leftMouseDownView,
selector = type == CPRightMouseUp ? @selector(rightMouseUp:) : @selector(mouseUp:);
[_leftMouseDownView mouseUp:anEvent]
if (!hitTestedView)
hitTestedView = [_windowView hitTest:point];
[hitTestedView performSelector:selector withObject:anEvent];
_leftMouseDownView = nil;
return;
case CPLeftMouseDown: _leftMouseDownView = [_windowView hitTest:point];
case CPLeftMouseDown:
case CPRightMouseDown: _leftMouseDownView = [_windowView hitTest:point];
if (_leftMouseDownView != _firstResponder && [_leftMouseDownView acceptsFirstResponder])
[self makeFirstResponder:_leftMouseDownView];
[CPApp activateIgnoringOtherApps:YES];
var theWindow = [anEvent window];
var theWindow = [anEvent window],
selector = type == CPRightMouseDown ? @selector(rightMouseDown:) : @selector(mouseDown:);
if ([theWindow isKeyWindow] || [theWindow becomesKeyOnlyIfNeeded] && ![_leftMouseDownView needsPanelToBecomeKey])
return [_leftMouseDownView mouseDown:anEvent];
return [_leftMouseDownView performSelector:selector withObject:anEvent];
else
{
// FIXME: delayed ordering?
[self makeKeyAndOrderFront:self];
if ([_leftMouseDownView acceptsFirstMouse:anEvent])
return [_leftMouseDownView mouseDown:anEvent]
return [_leftMouseDownView performSelector:selector withObject:anEvent];
}
break;
case CPLeftMouseDragged: if (!_leftMouseDownView)
case CPLeftMouseDragged:
case CPRightMouseDragged: if (!_leftMouseDownView)
return [[_windowView hitTest:point] mouseDragged:anEvent];
return [_leftMouseDownView mouseDragged:anEvent];
case CPRightMouseUp: return [_rightMouseDownView mouseUp:anEvent];
case CPRightMouseDown: _rightMouseDownView = [_windowView hitTest:point];
return [_rightMouseDownView mouseDown:anEvent];
case CPRightMouseDragged: return [_rightMouseDownView mouseDragged:anEvent];
var selector;
if (type == CPRightMouseDragged)
{
selector = @selector(rightMouseDragged:)
if (![_leftMouseDownView respondsToSelector:selector])
selector = nil;
}
if (!selector)
selector = @selector(mouseDragged:)
return [_leftMouseDownView performSelector:selector withObject:anEvent];
case CPMouseMoved: if (!_acceptsMouseMovedEvents)
return;
@@ -1494,10 +1524,11 @@ CPTexturedBackgroundWindowMask
*/
- (void)resignKeyWindow
{
if (_firstResponder != self && [_firstResponder respondsToSelector:@selector(resignKeyWindow)])
if (_firstResponder !== self && [_firstResponder respondsToSelector:@selector(resignKeyWindow)])
[_firstResponder resignKeyWindow];
CPApp._keyWindow = nil;
if (CPApp._keyWindow === self)
CPApp._keyWindow = nil;
[[CPNotificationCenter defaultCenter]
postNotificationName:CPWindowDidResignKeyNotification
@@ -1858,7 +1889,8 @@ CPTexturedBackgroundWindowMask
postNotificationName:CPWindowDidResignMainNotification
object:self];
CPApp._mainWindow = nil;
if (CPApp._mainWindow === self)
CPApp._mainWindow = nil;
}
- (void)_updateMainAndKeyWindows
@@ -1866,9 +1898,6 @@ CPTexturedBackgroundWindowMask
var allWindows = [CPApp orderedWindows],
windowCount = [allWindows count];
if (!windowCount)
return;
if ([self isKeyWindow])
{
var keyWindow = [CPApp keyWindow];
@@ -1893,11 +1922,10 @@ CPTexturedBackgroundWindowMask
}
if (![CPApp keyWindow])
[keyWindow makeKeyWindow];
[menuWindow makeKeyWindow];
}
}
if ([self isMainWindow])
{
var mainWindow = [CPApp mainWindow];
-19
View File
@@ -322,25 +322,6 @@
return _documents;
}
- (void)setViewController:(CPViewController)aViewController
{
var containerView = [self viewControllerContainerView] || [[self window] contentView],
view = [_viewController view],
frame = view ? [view frame] : [containerView bounds];
[view removeFromSuperview];
_viewController = aViewController;
view = [_viewController view];
if (view)
{
[view setFrame:frame];
[containerView addSubview:view];
}
}
- (void)setViewControllerContainerView:(CPView)aView
{
_viewControllerContainerView = aView;
+6 -1
View File
@@ -171,12 +171,17 @@ var CPCibObjectDataKey = @"CPCibObjectDataKey";
- (void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data
{
// FIXME: Why aren't we getting connection:didFailWithError:
if (!data)
return [self connection:aConnection didFailWithError:nil];
_data = [CPData dataWithRawString:data];
}
- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPError)anError
{
alert("cib: connection failed.");
if ([_loadDelegate respondsToSelector:@selector(cibDidFailToLoad:)])
[_loadDelegate cibDidFailToLoad:self];
_loadDelegate = nil;
}
+5
View File
@@ -118,4 +118,9 @@ var CPCibOwner = @"CPCibOwner";
[_loadDelegate cibDidFinishLoading:aCib];
}
- (void)cibDidFailToLoad:(CPCib)aCib
{
[_loadDelegate cibDidFailToLoad:aCib];
}
@end
+1 -2
View File
@@ -777,8 +777,7 @@ if (_DOMContentsElement && aLayer._zPosition > _DOMContentsElement.style.zIndex)
@ignore
*/
+ (void)runLoopUpdateLayers
{if (window.oops) {alert(window.latest); objj_debug_print_backtrace();}
window.loop = true;
{
for (UID in CALayerRegisteredRunLoopUpdates)
{
var layer = CALayerRegisteredRunLoopUpdates[UID],
+1 -1
View File
@@ -210,7 +210,7 @@ function CGPathAddQuadCurveToPoint(aPath, aTransform, cpx, cpy, x, y)
if (aTransform)
{
cp = _CGPointApplyAffineTransform(control, aTransform);
cp = _CGPointApplyAffineTransform(cp, aTransform);
end = _CGPointApplyAffineTransform(end, aTransform);
}
+1 -1
View File
@@ -20,7 +20,7 @@ appKitTask = framework ("AppKit", function(appKitTask)
appKitTask.setEmail("feedback @nospam@ 280north.com");
appKitTask.setSummary("AppKit classes for Cappuccino");
appKitTask.setIdentifier("com.280n.AppKit");
appKitTask.setVersion("0.8.0");
appKitTask.setVersion(getCappuccinoVersion());
appKitTask.setLicense(BundleTask.License.LGPL_v2_1);
appKitTask.setSources(AppKitFiles);
appKitTask.setResources(new FileList("Resources/**/*"));
+1
View File
@@ -46,6 +46,7 @@ var PrimaryPlatformWindow = NULL;
CPDictionary _windowLayers;
BOOL _mouseIsDown;
BOOL _mouseDownIsRightClick;
CPWindow _mouseDownWindow;
CPTimeInterval _lastMouseUp;
CPTimeInterval _lastMouseDown;
+58 -35
View File
@@ -22,9 +22,10 @@
#include "../CoreGraphics/CGGeometry.h"
var DOMSpanElement = nil,
DOMIFrameElement = nil,
DefaultFont = nil;
var DOMFixedWidthSpanElement = nil,
DOMFlexibleWidthSpanElement = nil,
DOMIFrameElement = nil,
DefaultFont = nil;
@implementation CPPlatformString : CPBasePlatformString
{
@@ -37,25 +38,30 @@ var DOMSpanElement = nil,
+ (void)createDOMElements
{
var style;
DOMIFrameElement = document.createElement("iframe");
// necessary for Safari caching bug:
DOMIFrameElement.name = "iframe_" + FLOOR(RAND() * 10000);
DOMIFrameElement.style.position = "absolute";
DOMIFrameElement.style.left = "-100px";
DOMIFrameElement.style.top = "-100px";
DOMIFrameElement.style.width = "1px";
DOMIFrameElement.style.height = "1px";
DOMIFrameElement.style.borderWidth = "0px";
DOMIFrameElement.style.overflow = "hidden";
DOMIFrameElement.style.zIndex = 100000000000;
DOMIFrameElement.className = "cpdontremove";
style = DOMIFrameElement.style;
style.position = "absolute";
style.left = "-100px";
style.top = "-100px";
style.width = "1px";
style.height = "1px";
style.borderWidth = "0px";
style.overflow = "hidden";
style.zIndex = 100000000000;
var bodyElement = [CPPlatform mainBodyElement];
bodyElement.appendChild(DOMIFrameElement);
var DOMIFrameDocument = (DOMIFrameElement.contentDocument || DOMIFrameElement.contentWindow.document);
DOMIFrameDocument.write("<html><head></head><body></body></html>");
DOMIFrameDocument.write('<!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"><head></head><body></body></html>');
DOMIFrameDocument.close();
// IE needs this wide <div> to prevent unwanted text wrapping:
@@ -65,14 +71,39 @@ var DOMSpanElement = nil,
DOMIFrameDocument.body.appendChild(DOMDivElement);
DOMSpanElement = DOMIFrameDocument.createElement("span");
DOMSpanElement.style.position = "absolute";
DOMSpanElement.style.whiteSpace = "pre";
DOMSpanElement.style.visibility = "visible";
DOMSpanElement.style.padding = "0px";
DOMSpanElement.style.margin = "0px";
DOMFlexibleWidthSpanElement = DOMIFrameDocument.createElement("span");
style = DOMFlexibleWidthSpanElement.style;
style.position = "absolute";
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.whiteSpace = "pre";
DOMDivElement.appendChild(DOMSpanElement);
DOMFixedWidthSpanElement = DOMIFrameDocument.createElement("span");
style = DOMFixedWidthSpanElement.style;
style.display = "block";
style.position = "absolute";
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.width = "1px";
style.wordWrap = "break-word";
try
{
style.whiteSpace = "pre";
style.whiteSpace = "-o-pre-wrap";
style.whiteSpace = "-pre-wrap";
style.whiteSpace = "-moz-pre-wrap";
style.whiteSpace = "pre-wrap";
}
catch(e)
{
//some versions of IE throw exceptions for unsupported properties.
style.whiteSpace = "pre";
}
DOMDivElement.appendChild(DOMFlexibleWidthSpanElement);
DOMDivElement.appendChild(DOMFixedWidthSpanElement);
}
+ (CGSize)sizeOfString:(CPString)aString withFont:(CPFont)aFont forWidth:(float)aWidth
@@ -88,31 +119,23 @@ var DOMSpanElement = nil,
if (!DOMIFrameElement)
[self createDOMElements];
var style = DOMSpanElement.style;
var span;
if (!aWidth)
{
style.width = "";
style.whiteSpace = "pre";
}
span = DOMFlexibleWidthSpanElement;
else
{
style.width = ROUND(aWidth) + "px";
style.wordWrap = "break-word";
style.whiteSpace = "-o-pre-wrap";
style.whiteSpace = "-pre-wrap";
style.whiteSpace = "-moz-pre-wrap";
style.whiteSpace = "pre-wrap";
span = DOMFixedWidthSpanElement;
span.style.width = ROUND(aWidth) + "px";
}
style.font = [aFont cssString];
span.style.font = [aFont cssString];
if (CPFeatureIsCompatible(CPJavascriptInnerTextFeature))
DOMSpanElement.innerText = aString;
span.innerText = aString;
else if (CPFeatureIsCompatible(CPJavascriptTextContentFeature))
DOMSpanElement.textContent = aString;
span.textContent = aString;
return _CGSizeMake(DOMSpanElement.clientWidth, DOMSpanElement.clientHeight);
return _CGSizeMake(span.clientWidth, span.clientHeight);
}
@end
+60 -7
View File
@@ -127,7 +127,10 @@ var PlatformWindows = [CPSet set];
// Define up here so compressor knows about em.
var CPDOMEventGetClickCount,
CPDOMEventStop,
StopDOMEventPropagation;
StopDOMEventPropagation,
StopContextMenuDOMEventPropagation;
var _DOMEventGuard;
//right now we hard code q, w, r and t as keys to propogate
//these aren't normal keycodes, they are with modifier key codes
@@ -255,6 +258,19 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
// Make sure the pastboard element is blurred.
_DOMPasteboardElement.blur();
// Create a full screen div to protect against iframes and other elements from consuming events during tracking
// FIXME: multiple windows
_DOMEventGuard = theDocument.createElement("div");
_DOMEventGuard.style.position = "absolute";
_DOMEventGuard.style.top = "0px";
_DOMEventGuard.style.left = "0px";
_DOMEventGuard.style.width = "100%";
_DOMEventGuard.style.height = "100%";
_DOMEventGuard.style.zIndex = "999";
_DOMEventGuard.style.display = "none";
_DOMEventGuard.className = "cpdontremove";
_DOMBodyElement.appendChild(_DOMEventGuard);
}
- (void)registerDOMWindow
@@ -297,6 +313,10 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
mouseEventImplementation = class_getMethodImplementation(theClass, mouseEventSelector),
mouseEventCallback = function (anEvent) { mouseEventImplementation(self, nil, anEvent); },
contextMenuEventSelector = @selector(contextMenuEvent:),
contextMenuEventImplementation = class_getMethodImplementation(theClass, contextMenuEventSelector),
contextMenuEventCallback = function (anEvent) { return contextMenuEventImplementation(self, nil, anEvent); },
scrollEventSelector = @selector(scrollEvent:),
scrollEventImplementation = class_getMethodImplementation(theClass, scrollEventSelector),
scrollEventCallback = function (anEvent) { scrollEventImplementation(self, nil, anEvent); },
@@ -320,6 +340,7 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
theDocument.addEventListener("mouseup", mouseEventCallback, NO);
theDocument.addEventListener("mousedown", mouseEventCallback, NO);
theDocument.addEventListener("mousemove", mouseEventCallback, NO);
theDocument.addEventListener("contextmenu", contextMenuEventCallback, NO);
theDocument.addEventListener("beforecopy", copyEventCallback, NO);
theDocument.addEventListener("beforecut", copyEventCallback, NO);
@@ -347,6 +368,7 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
theDocument.removeEventListener("mouseup", mouseEventCallback, NO);
theDocument.removeEventListener("mousedown", mouseEventCallback, NO);
theDocument.removeEventListener("mousemove", mouseEventCallback, NO);
theDocument.removeEventListener("contextmenu", contextMenuEventCallback, NO);
theDocument.removeEventListener("keyup", keyEventCallback, NO);
theDocument.removeEventListener("keydown", keyEventCallback, NO);
@@ -379,6 +401,7 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
theDocument.attachEvent("onmousedown", mouseEventCallback);
theDocument.attachEvent("onmousemove", mouseEventCallback);
theDocument.attachEvent("ondblclick", mouseEventCallback);
theDocument.attachEvent("oncontextmenu", contextMenuEventCallback);
theDocument.attachEvent("onkeyup", keyEventCallback);
theDocument.attachEvent("onkeydown", keyEventCallback);
@@ -401,6 +424,7 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
theDocument.detachEvent("onmousedown", mouseEventCallback);
theDocument.detachEvent("onmousemove", mouseEventCallback);
theDocument.detachEvent("ondblclick", mouseEventCallback);
theDocument.detachEvent("oncontextmenu", contextMenuEventCallback);
theDocument.detachEvent("onkeyup", keyEventCallback);
theDocument.detachEvent("onkeydown", keyEventCallback);
@@ -789,7 +813,6 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
}
}
- (void)_checkPasteboardElement
{
var value = _DOMPasteboardElement.value;
@@ -1032,11 +1055,12 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
{
if(_mouseIsDown)
{
event = _CPEventFromNativeMouseEvent(aDOMEvent, CPLeftMouseUp, location, modifierFlags, timestamp, windowNumber, nil, -1, CPDOMEventGetClickCount(_lastMouseUp, timestamp, location), 0);
event = _CPEventFromNativeMouseEvent(aDOMEvent, _mouseDownIsRightClick ? CPRightMouseUp : CPLeftMouseUp, location, modifierFlags, timestamp, windowNumber, nil, -1, CPDOMEventGetClickCount(_lastMouseUp, timestamp, location), 0);
_mouseIsDown = NO;
_lastMouseUp = event;
_mouseDownWindow = nil;
_mouseDownIsRightClick = NO;
}
if(_DOMEventMode)
@@ -1076,8 +1100,13 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
_DOMBodyElement.style["-khtml-user-drag"] = "element";
}
event = _CPEventFromNativeMouseEvent(aDOMEvent, CPLeftMouseDown, location, modifierFlags, timestamp, windowNumber, nil, -1, CPDOMEventGetClickCount(_lastMouseDown, timestamp, location), 0);
var button = aDOMEvent.button;
_mouseDownIsRightClick = button == 2 || (button == 0 && modifierFlags & CPControlKeyMask);
StopContextMenuDOMEventPropagation = YES;
event = _CPEventFromNativeMouseEvent(aDOMEvent, _mouseDownIsRightClick ? CPRightMouseDown : CPLeftMouseDown, location, modifierFlags, timestamp, windowNumber, nil, -1, CPDOMEventGetClickCount(_lastMouseDown, timestamp, location), 0);
_mouseIsDown = YES;
_lastMouseDown = event;
}
@@ -1087,7 +1116,7 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
if (_DOMEventMode)
return;
event = _CPEventFromNativeMouseEvent(aDOMEvent, _mouseIsDown ? CPLeftMouseDragged : CPMouseMoved, location, modifierFlags, timestamp, windowNumber, nil, -1, 1, 0);
event = _CPEventFromNativeMouseEvent(aDOMEvent, _mouseIsDown ? (_mouseDownIsRightClick ? CPRightMouseDragged : CPLeftMouseDragged) : CPMouseMoved, location, modifierFlags, timestamp, windowNumber, nil, -1, 1, 0);
}
var isDragging = [[CPDragServer sharedDragServer] isDragging];
@@ -1102,10 +1131,21 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
if (StopDOMEventPropagation && (!supportsNativeDragAndDrop || type !== "mousedown" && !isDragging))
CPDOMEventStop(aDOMEvent, self);
// if there are any tracking event listeners then show the event guard so we don't lose events to iframes
_DOMEventGuard.style.display = (CPApp._eventListeners.length === 0) ? "none" : "";
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
}
(CPArray)orderedWindowsAtLevel:(int)aLevel
- (void)contextMenuEvent:(DOMEvent)aDOMEvent
{
if (StopContextMenuDOMEventPropagation)
CPDOMEventStop(aDOMEvent, self);
return !StopContextMenuDOMEventPropagation;
}
- (CPArray)orderedWindowsAtLevel:(int)aLevel
{
var layer = [self layerAtLevel:aLevel create:NO];
@@ -1246,6 +1286,19 @@ var supportsNativeDragAndDrop = [CPPlatform supportsDragAndDrop];
return !StopDOMEventPropagation;
}
- (void)_propagateContextMenuDOMEvent:(BOOL)aFlag
{
if (aFlag && CPBrowserIsEngine(CPGeckoBrowserEngine))
StopDOMEventPropagation = !aFlag;
StopContextMenuDOMEventPropagation = !aFlag;
}
- (BOOL)_willPropagateContextMenuDOMEvent
{
return StopContextMenuDOMEventPropagation;
}
- (CPWindow)hitTest:(CPPoint)location
{
if (self._only)
Binary file not shown.

After

Width:  |  Height:  |  Size: 304 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 321 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 340 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 B

+41 -9
View File
@@ -721,17 +721,49 @@
+ (CPButtonBar)themedButtonBar
{
var buttonBar = [[CPButtonBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 26.0)],
color = [CPColor colorWithPatternImage:[[CPThreePartImage alloc] initWithImageSlices:
[
[_CPCibCustomResource imageResourceWithName:"buttonbar-bezel.png" size:CGSizeMake(1.0, 26.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-bezel.png" size:CGSizeMake(1.0, 26.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-bezel-right.png" size:CGSizeMake(13.0, 26.0)]
]
isVertical:NO]];
var buttonBar = [[CPButtonBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 140.0, 26.0)],
color = [CPColor colorWithPatternImage:[_CPCibCustomResource imageResourceWithName:"buttonbar-bezel.png" size:CGSizeMake(1.0, 26.0)]];
[buttonBar setHasResizeControl:YES];
[buttonBar setValue:color forThemeAttribute:@"bezel-color"];
var resizeColor = [CPColor colorWithPatternImage:[_CPCibCustomResource imageResourceWithName:"buttonbar-resize-control.png" size:CGSizeMake(5.0, 10.0)]];
[buttonBar setValue:CGSizeMake(5.0, 10.0) forThemeAttribute:@"resize-control-size"];
[buttonBar setValue:CGInsetMake(9.0, 4.0, 7.0, 4.0) forThemeAttribute:@"resize-control-inset"];
[buttonBar setValue:resizeColor forThemeAttribute:@"resize-control-color"];
var buttonBezelColor = [CPColor colorWithPatternImage:[[CPThreePartImage alloc] initWithImageSlices:
[
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-left.png" size:CGSizeMake(2.0, 25.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-center.png" size:CGSizeMake(1.0, 25.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-right.png" size:CGSizeMake(2.0, 25.0)]
]
isVertical:NO]],
buttonBezelHighlightedColor = [CPColor colorWithPatternImage:[[CPThreePartImage alloc] initWithImageSlices:
[
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-highlighted-left.png" size:CGSizeMake(2.0, 25.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-highlighted-center.png" size:CGSizeMake(1.0, 25.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-highlighted-right.png" size:CGSizeMake(2.0, 25.0)]
]
isVertical:NO]],
buttonBezelDisabledColor = [CPColor colorWithPatternImage:[[CPThreePartImage alloc] initWithImageSlices:
[
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-disabled-left.png" size:CGSizeMake(2.0, 25.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-disabled-center.png" size:CGSizeMake(1.0, 25.0)],
[_CPCibCustomResource imageResourceWithName:"buttonbar-button-bezel-disabled-right.png" size:CGSizeMake(2.0, 25.0)]
]
isVertical:NO]];
[buttonBar setValue:buttonBezelColor forThemeAttribute:@"button-bezel-color"];
[buttonBar setValue:buttonBezelHighlightedColor forThemeAttribute:@"button-bezel-color" inState:CPThemeStateHighlighted];
[buttonBar setValue:buttonBezelDisabledColor forThemeAttribute:@"button-bezel-color" inState:CPThemeStateDisabled];
[buttonBar setButtons:[[CPButtonBar plusButton], [CPButtonBar minusButton], [self themedPullDownMenu]]];
return buttonBar;
}
+1 -1
View File
@@ -10,7 +10,7 @@ blendKitTask = framework ("BlendKit", function(blendKitTask)
blendKitTask.setBuildPath(FILE.join($BUILD_DIR, $CONFIGURATION));
blendKitTask.setIdentifier("com.280n.BlendKit");
blendKitTask.setVersion("0.8.0");
blendKitTask.setVersion(getCappuccinoVersion());
blendKitTask.setAuthor("280 North, Inc.");
blendKitTask.setEmail("feedback @nospam@ 280north.com");
blendKitTask.setSummary("BlendKit classes for Cappuccino");
+20 -8
View File
@@ -5,13 +5,18 @@
{
}
- (void)_init
{
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview.png", CGSizeMake(1.0, 23.0))]];
}
- (id)initWithFrame:(CGRect)aFrame
{
if (self = [super initWithFrame:aFrame])
{
[self setBackgroundColor:[CPColor colorWithPatternImage:CPAppKitImage("tableview-headerview.png", CGSizeMake(1.0, 23.0))]];
[self _init];
}
return self;
}
@@ -20,16 +25,23 @@
var context = [[CPGraphicsContext currentContext] graphicsPort];
CGContextSetStrokeColor(context, [CPColor colorWithHexString:@"dce0e2"]);
var points = [
CGPointMake(aRect.origin.x, aRect.origin.y),
CGPointMake(aRect.origin.x + aRect.size.width, aRect.origin.y),
var points = [
CGPointMake(aRect.origin.x, aRect.origin.y + 0.5),
CGPointMake(aRect.origin.x, aRect.origin.y + aRect.size.height)
];
CGContextStrokeLineSegments(context, points, 2);
}
- (id)initWithCoder:(CPCoder)aCoder
{
self = [super initWithCoder:aCoder];
{
[self _init];
}
return self;
}
@end
+25 -38
View File
@@ -332,7 +332,8 @@ var HORIZONTAL_MARGIN = 3.0,
hasDOMTextElement = !!_DOMTextElement;
// Create or destroy the DOM Text Element as necessary
if (needsDOMTextElement !== hasDOMTextElement)
if (needsDOMTextElement !== hasDOMTextElement)
{
if (hasDOMTextElement)
{
_DOMElement.removeChild(_DOMTextElement);
@@ -361,6 +362,7 @@ var HORIZONTAL_MARGIN = 3.0,
// We have to set all these values now.
_flags |= _CPImageAndTextViewTextChangedFlag | _CPImageAndTextViewFontChangedFlag | _CPImageAndTextViewLineBreakModeChangedFlag;
}
}
var textStyle = hasDOMTextElement ? _DOMTextElement.style : nil;
@@ -369,6 +371,7 @@ var HORIZONTAL_MARGIN = 3.0,
hasDOMTextShadowElement = !!_DOMTextShadowElement;
if (needsDOMTextShadowElement !== hasDOMTextShadowElement)
{
if (hasDOMTextShadowElement)
{
_DOMElement.removeChild(_DOMTextShadowElement);
@@ -386,6 +389,7 @@ var HORIZONTAL_MARGIN = 3.0,
shadowStyle.font = [_font ? _font : [CPFont systemFontOfSize:12.0] cssString];
shadowStyle.position = "absolute";
shadowStyle.whiteSpace = textStyle.whiteSpace;
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.color = [_textShadowColor cssString];
shadowStyle.zIndex = 150;
@@ -394,7 +398,6 @@ var HORIZONTAL_MARGIN = 3.0,
if (document.attachEvent)
{
shadowStyle.overflow = textStyle.overflow;
shadowStyle.wordWrap = textStyle.wordWrap;
}
else
{
@@ -408,6 +411,7 @@ var HORIZONTAL_MARGIN = 3.0,
_flags |= _CPImageAndTextViewTextChangedFlag; //sigh...
}
}
var shadowStyle = hasDOMTextShadowElement ? _DOMTextShadowElement.style : nil;
@@ -447,9 +451,7 @@ var HORIZONTAL_MARGIN = 3.0,
case CPLineBreakByClipping: textStyle.overflow = "hidden";
textStyle.textOverflow = "clip";
textStyle.whiteSpace = "pre";
if (document.attachEvent)
textStyle.wordWrap = "normal";
textStyle.wordWrap = "normal";
break;
@@ -459,26 +461,23 @@ var HORIZONTAL_MARGIN = 3.0,
case CPLineBreakByTruncatingTail: textStyle.textOverflow = "ellipsis";
textStyle.whiteSpace = "nowrap";
textStyle.overflow = "hidden";
if (document.attachEvent)
textStyle.wordWrap = "normal";
textStyle.wordWrap = "normal";
break;
case CPLineBreakByCharWrapping:
case CPLineBreakByWordWrapping: if (document.attachEvent)
{
case CPLineBreakByWordWrapping: textStyle.wordWrap = "break-word";
try {
textStyle.whiteSpace = "pre";
textStyle.wordWrap = "break-word";
}
else
{
textStyle.whiteSpace = "-o-pre-wrap";
textStyle.whiteSpace = "-pre-wrap";
textStyle.whiteSpace = "-moz-pre-wrap";
textStyle.whiteSpace = "pre-wrap";
}
catch (e) {
//internet explorer doesn't like these properties
textStyle.whiteSpace = "pre";
}
textStyle.overflow = "hidden";
textStyle.textOverflow = "clip";
@@ -490,7 +489,6 @@ var HORIZONTAL_MARGIN = 3.0,
{
if (document.attachEvent)
{
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.overflow = textStyle.overflow;
}
else
@@ -499,6 +497,7 @@ var HORIZONTAL_MARGIN = 3.0,
shadowStyle.overflowY = textStyle.overflowY;
}
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.whiteSpace = textStyle.whiteSpace;
shadowStyle.textOverflow = textStyle.textOverflow;
}
@@ -510,6 +509,7 @@ var HORIZONTAL_MARGIN = 3.0,
// Create or destroy DOM Image element
if (needsDOMImageElement !== hasDOMImageElement)
{
if (hasDOMImageElement)
{
_DOMElement.removeChild(_DOMImageElement);
@@ -539,8 +539,8 @@ var HORIZONTAL_MARGIN = 3.0,
_DOMElement.appendChild(_DOMImageElement);
hasDOMImageElement = YES;
}
#endif
}
}
var size = [self bounds].size,
textRect = _CGRectMake(0.0, 0.0, size.width, size.height);
@@ -572,67 +572,54 @@ var HORIZONTAL_MARGIN = 3.0,
imageHeight *= scale;
}
#if PLATFORM(DOM)
_DOMImageElement.width = imageWidth;
_DOMImageElement.height = imageHeight;
imageStyle.width = imageWidth + "px";
imageStyle.height = imageHeight + "px";
#endif
imageStyle.width = MAX(imageWidth, 0) + "px";
imageStyle.height = MAX(imageHeight, 0) + "px";
if (_imagePosition === CPImageBelow)
{
#if PLATFORM(DOM)
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
imageStyle.top = FLOOR(size.height - imageHeight) + "px";
#endif
textRect.size.height = size.height - imageHeight - VERTICAL_MARGIN;
}
else if (_imagePosition === CPImageAbove)
{
#if PLATFORM(DOM)
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, FLOOR(centerX - imageWidth / 2.0), 0);
#endif
textRect.origin.y += imageHeight + VERTICAL_MARGIN;
textRect.size.height = size.height - imageHeight - VERTICAL_MARGIN;
}
else if (_imagePosition === CPImageLeft)
{
#if PLATFORM(DOM)
imageStyle.top = FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = "0px";
#endif
textRect.origin.x = imageWidth + HORIZONTAL_MARGIN;
textRect.size.width -= imageWidth + HORIZONTAL_MARGIN;
}
else if (_imagePosition === CPImageRight)
{
#if PLATFORM(DOM)
imageStyle.top = FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = FLOOR(size.width - imageWidth) + "px";
#endif
textRect.size.width -= imageWidth + HORIZONTAL_MARGIN;
}
else if (_imagePosition === CPImageOnly)
{
#if PLATFORM(DOM)
imageStyle.top = FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
#endif
}
}
#if PLATFORM(DOM)
if (hasDOMTextElement)
{
var textRectX = _CGRectGetMinX(textRect),
textRectY = _CGRectGetMinY(textRect),
textRectWidth = _CGRectGetWidth(textRect),
textRectHeight = _CGRectGetHeight(textRect);
if (_verticalAlignment !== CPTopVerticalTextAlignment)
{
if (!_textSize)
@@ -659,8 +646,8 @@ var HORIZONTAL_MARGIN = 3.0,
textStyle.top = ROUND(textRectY) + "px";
textStyle.left = ROUND(textRectX) + "px";
textStyle.width = ROUND(textRectWidth) + "px";
textStyle.height = ROUND(textRectHeight) + "px";
textStyle.width = MAX(ROUND(textRectWidth), 0) + "px";
textStyle.height = MAX(ROUND(textRectHeight), 0) + "px";
if (shadowStyle)
{
@@ -669,8 +656,8 @@ var HORIZONTAL_MARGIN = 3.0,
shadowStyle.top = ROUND(textRectY + _textShadowOffset.height) + "px";
shadowStyle.left = ROUND(textRectX + _textShadowOffset.width) + "px";
shadowStyle.width = ROUND(textRectWidth) + "px";
shadowStyle.height = ROUND(textRectHeight) + "px";
shadowStyle.width = MAX(ROUND(textRectWidth), 0) + "px";
shadowStyle.height = MAX(ROUND(textRectHeight), 0) + "px";
}
}
#endif
+5 -1
View File
@@ -8,7 +8,7 @@ new FileList("**/*").exclude("Jakefile").forEach(function(aFilename)
if (!FILE.isFile(aFilename))
return;
var buildFilename = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", aFilename);
var buildFilename = FILE.join($BUILD_CJS_CAPPUCCINO, aFilename);
filedir (buildFilename, [aFilename], function ()
{
@@ -27,3 +27,7 @@ new FileList("**/*").exclude("Jakefile").forEach(function(aFilename)
task ("build", buildFilename);
CLOBBER.include(buildFilename);
});
task ("build", function() {
setPackageMetadata(FILE.join($BUILD_CJS_CAPPUCCINO, "package.json"));
});
+175 -103
View File
@@ -8,6 +8,7 @@ require("narwhal").ensureEngine("rhino");
var FILE = require("file");
var OS = require("os");
var UTIL = require("util");
var stream = require("term").stream;
var parser = new (require("args").Parser)();
@@ -24,6 +25,10 @@ parser.option("-F", "--framework", "frameworks")
.push()
.help("Add a frameworks directory, relative to INPUT_PROJECT (default: ['Frameworks'])");
parser.option("-P", "--path", "paths")
.push()
.help("Add a path (relative to the application root) to inline.");
parser.option("-f", "--force", "force")
.def(false)
.set(true)
@@ -34,6 +39,11 @@ parser.option("--index", "index")
.set()
.help("The root HTML file to modify (default: index.html)");
parser.option("-s", "--split", "number", "split")
.natural()
.def(0)
.help("Split into multiple files");
parser.option("-v", "--verbose", "verbose")
.def(false)
.set(true)
@@ -81,32 +91,27 @@ function main(args)
var flattener = new ObjectiveJFlattener(rootPath);
flattener.options = options;
flattener.setIncludePaths(frameworks);
flattener.setEnvironments([environment, "ObjJ"]);
print("Loading application.");
flattener.load(mainPath);
flattener.finishLoading();
var rootResources = flattener.require("objective-j").StaticResource.rootResources();
print("Loading default theme.");
flattener.require("objective-j").objj_eval("("+(function() {
var blend = [[CPThemeBlend alloc] initWithContentsOfURL:[[CPBundle bundleForClass:[CPApplication class]] pathForResource:[CPApplication defaultThemeName] + ".blend"]];
[blend loadWithDelegate:nil];
})+")")();
var root = rootResources["file:"];
// FIXME: shouldn't have to do this manually
var components = rootPath.split("/").slice(0, -1);
components[0] = "/";
var node = root;
while (components.length) {
node = node.children()[components.shift()];
}
applicationRoot = node;
print(applicationRoot.toString());
var applicationJS = flattener.buildApplicationJS(applicationRoot);
var applicationJSs = flattener.buildApplicationJS();
FILE.copyTree(rootPath, outputPath);
outputPath.join("Application.js").write(applicationJS);
applicationJSs.forEach(function(applicationJS, n) {
outputPath.join("Application"+(n||"")+".js").write(applicationJS);
});
rewriteMainHTML(outputPath.join(options.index));
}
@@ -115,118 +120,185 @@ function main(args)
function ObjectiveJFlattener(rootPath) {
ObjectiveJRuntimeAnalyzer.apply(this, arguments);
this.resourceBuffer = [];
this.bundleBuffer = [];
this.filesToCache = {};
this.fileCacheBuffer = [];
this.functionsBuffer = [];
this._outputBundles = {};
}
ObjectiveJFlattener.prototype = Object.create(ObjectiveJRuntimeAnalyzer.prototype);
ObjectiveJFlattener.prototype.buildApplicationJS = function(applicationRoot) {
this.serializeStaticResources(applicationRoot);
this.serializeStaticFileExecutables();
ObjectiveJFlattener.prototype.buildApplicationJS = function() {
var buffer = []
this.setupFileCache();
this.serializeFunctions();
this.serializeFileCache();
buffer.push("(function(){");
var applicationJSs = [];
buffer.push("var appURL = new CFURL('.', ObjectiveJ.pageURL);")
buffer.push(this.bundleBuffer.join("\n"));
buffer.push("var nodeStack = [];");
buffer.push("var applicationRoot = ObjectiveJ.StaticResource.resourceAtURL(appURL, true);");
buffer.push("var currentNode = null;");
buffer.push("var newNode;");
buffer.push(this.resourceBuffer.join("\n"));
buffer.push("})();");
buffer.push(this.functionsBuffer.join("\n"));
buffer.push("ObjectiveJ.bootstrap();");
return buffer.join("\n");
}
ObjectiveJFlattener.prototype.serializeStaticFileExecutables = function() {
this.require("objective-j").FileExecutable.allFileExecutables().forEach(function(aFileExecutable) {
var deps = aFileExecutable.fileDependencies().map(function(dependency) {
return "new ObjectiveJ.FileDependency(new CFURL("+JSON.stringify(dependency.path())+"),"+JSON.stringify(dependency.isLocal())+")"
}).join(",");
var func = aFileExecutable._function.toString();
// HACK
func = func.replace(", require, exports, module, system, print, window", "");
this.functionsBuffer.push("var path = "+JSON.stringify(this.rootPath.relative(aFileExecutable.path()).toString())+";");
this.functionsBuffer.push("new ObjectiveJ.FileExecutable(path,"+
"new ObjectiveJ.Executable(null, ["+deps+"], path, "+func+"));");
}, this);
}
ObjectiveJFlattener.prototype.serializeStaticResources = function(node, depth) {
depth = depth || 0;
var bundle = this.context.global.CFBundle.bundleContainingURL(node.URL());
if (!bundle) {
stream.print("\0yellow(Warning:\0) No bundle for path: \0cyan("+node.URL()+"\0)");
}
else if (!this._outputBundles[bundle.path()]) {
this._outputBundles[bundle.path()] = bundle;
stream.print("Writing bundle: \0cyan("+bundle.path()+"\0)");
print(bundle.infoDictionary())
var relative = this.rootPath.relative(bundle.path()).toString();
this.bundleBuffer.push("var bundle = new CFBundle("+(relative ? JSON.stringify(relative) : "appURL")+");");
this.bundleBuffer.push("bundle._loadStatus = " + (1<<4) + ";");
if (bundle.infoDictionary()) {
this.bundleBuffer.push("bundle._infoDictionary = CFPropertyList.propertyListFromString(" +
JSON.stringify(CPPropertyListCreateData(bundle.infoDictionary()).rawString()) + ");");
}
}
// not the root node:
if (depth > 0) {
this.resourceBuffer.push("newNode = new ObjectiveJ.StaticResource(" +
JSON.stringify(node.name()) +
", currentNode, " +
JSON.stringify(node.isDirectory()) + ", " +
JSON.stringify(node.isResolved()) + ");");
if (this.options.split === 0) {
var buffer = [];
buffer.push("var baseURL = new CFURL(\".\", ObjectiveJ.pageURL);");
buffer.push(this.fileCacheBuffer.join("\n"));
buffer.push(this.functionsBuffer.join("\n"));
buffer.push("ObjectiveJ.bootstrap();");
applicationJSs.push(buffer.join("\n"));
} else {
this.resourceBuffer.push("newNode = applicationRoot;");
var appFilesCount = this.options.split;
var buffers = [];
for (var i = 0; i <= appFilesCount; i++)
buffers.push([]);
var chunks = this.fileCacheBuffer.concat(this.functionsBuffer).sort(function(chunkA, chunkB) {
return chunkA.length - chunkB.length;
});
// try to equally distribute the chunks. could be better but good enough for now.
var n = 0;
while (chunks.length) {
buffers[(n++ % appFilesCount) + 1].push(chunks.pop());
}
buffers[0].push("var baseURL = new CFURL(\".\", ObjectiveJ.pageURL);");
buffers[0].push("var appFilesCount = " + appFilesCount +";");
buffers[0].push("for (var i = 1; i <= appFilesCount; i++) {");
buffers[0].push(" var script = document.createElement(\"script\");");
buffers[0].push(" script.src = \"Application\"+i+\".js\";");
buffers[0].push(" script.onload = function() { if (--appFilesCount === 0) ObjectiveJ.bootstrap(); };");
buffers[0].push(" document.getElementsByTagName(\"head\")[0].appendChild(script);");
buffers[0].push("}");
buffers.forEach(function(buffer) {
applicationJSs.push(buffer.join("\n"));
});
}
// var contents = node.contents();
// if (contents) {
// this.resourceBuffer.push("newNode._contents = " + JSON.stringify(contents) + ";");
// }
return applicationJSs;
}
if (!node.children())
return;
ObjectiveJFlattener.prototype.serializeFunctions = function() {
var inlineFunctions = true;//this.options.inlineFunctions;
this.resourceBuffer.push("nodeStack.push(currentNode);");
this.resourceBuffer.push("currentNode = newNode;");
var outputFiles = {};
var children = node.children();
for (var name in children) {
this.serializeStaticResources(children[name], depth+1);
var _cachedExecutableFunctions = {};
this.require("objective-j").FileExecutable.allFileExecutables().forEach(function(executable) {
var path = executable.path();
if (inlineFunctions)
{
// stringify the function, replacing arguments
var functionString = executable._function.toString().replace(", require, exports, module, system, print, window", ""); // HACK
var relative = this.rootPath.relative(path).toString();
this.functionsBuffer.push("ObjectiveJ.FileExecutable._cacheFunction(new CFURL("+JSON.stringify(relative)+", baseURL),\n"+functionString+");");
}
var bundle = this.context.global.CFBundle.bundleContainingURL(path);
if (bundle && bundle.infoDictionary())
{
var executablePath = bundle.executablePath(),
relativeToBundle = FILE.relative(FILE.join(bundle.path(), ""), path);
if (executablePath)
{
if (inlineFunctions)
{
// remove the code since we're inlining the functions
executable._code = "alert("+JSON.stringify(relativeToBundle)+");";
}
if (!outputFiles[executablePath])
{
outputFiles[executablePath] = [];
outputFiles[executablePath].push("@STATIC;1.0;");
}
var fileContents = executable.toMarkedString();
outputFiles[executablePath].push("p;" + relativeToBundle.length + ";" + relativeToBundle);
outputFiles[executablePath].push("t;" + fileContents.length + ";" + fileContents);
// stream.print("Adding \0green(" + this.rootPath.relative(path) + "\0) to \0cyan(" + this.rootPath.relative(executablePath) + "\0)");
}
}
else
CPLog.warn("No bundle (or info dictionary for) " + rootPath.relative(path));
}, this);
for (var executablePath in outputFiles)
{
var relative = this.rootPath.relative(executablePath).toString();
var contents = outputFiles[executablePath].join("");
this.filesToCache[relative] = contents;
}
}
this.resourceBuffer.push("currentNode = nodeStack.pop();");
ObjectiveJFlattener.prototype.serializeFileCache = function() {
this.fileCacheBuffer.push(FILE.read(FILE.join(FILE.dirname(module.path), "..", "..", "cappuccino", "lib", "cappuccino", "objj-flatten-additions.js"), { charset:"UTF-8" }));
for (var relative in this.filesToCache) {
var contents = this.filesToCache[relative];
print("caching: " + relative + " => " + (contents == null ? 404 : 200));
if (contents == null)
this.fileCacheBuffer.push("CFHTTPRequest._cacheRequest(new CFURL("+JSON.stringify(relative)+", baseURL), 404);");
else
this.fileCacheBuffer.push("CFHTTPRequest._cacheRequest(new CFURL("+JSON.stringify(relative)+", baseURL), 200, {}, "+JSON.stringify(contents)+");");
}
}
ObjectiveJFlattener.prototype.setupFileCache = function() {
var paths = {};
UTIL.update(paths, this.requestedURLs);
this.options.paths.forEach(function(relativePath) {
paths[this.rootPath.join(relativePath)] = true;
}, this);
Object.keys(paths).forEach(function(absolute) {
var relative = this.rootPath.relative(absolute).toString();
if (relative.indexOf("..") === 0)
{
print("skipping (parent of app root): " + absolute);
return;
}
if (FILE.isFile(absolute))
{
// if (this.options.maxCachedSize && FILE.size(absolute) > this.options.maxCachedSize)
// {
// print("skipping (larger than "+this.options.maxCachedSize+" bytes): " + absolute);
// return;
// }
var contents = FILE.read(absolute, { charset : "UTF-8" });
this.filesToCache[relative] = contents;
} else {
this.filesToCache[relative] = null;
}
}, this);
}
// "$1" is the matching indentation
var scriptTagsBefore = '$1<script type = "text/javascript">\n$1 OBJJ_AUTO_BOOTSTRAP = false;\n$1</script>';
var scriptTagsAfter = '$1<script type = "text/javascript" src = "Application.js"></script>';
// enable CPLog:
// scriptTagsAfter = '$1<script type = "text/javascript">\n$1 CPLogRegister(CPLogConsole);\n$1</script>\n' + scriptTagsAfter;
function rewriteMainHTML(indexHTMLPath) {
if (indexHTMLPath.isFile()) {
var indexHTML = indexHTMLPath.read();
// inline the Application.js if it's smallish
var applicationJSPath = indexHTMLPath.dirname().join("Application.js");
if (applicationJSPath.size() < 10*1024) {
var applicationJS = applicationJSPath.read().split("\n").join("\n$1 ");
scriptTagsAfter = '$1<script type = "text/javascript">\n$1 '+applicationJS+'\n$1</script>'
}
// attempt to find Objective-J script tag and add ours
var newIndexHTML = indexHTML.replace(/([ \t]+)<script[^>]+Objective-J\.js[^>]+>(?:\s*<\/script>)?/,
scriptTagsBefore+'\n$&\n'+scriptTagsAfter);
+23
View File
@@ -0,0 +1,23 @@
var FILE = require("file");
var sprintf = require("printf").sprintf;
var pkg = null;
function getPackage() {
if (!pkg)
pkg = JSON.parse(FILE.path(module.path).dirname().dirname().join("package.json").read({ charset : "UTF-8" }));
return pkg;
}
exports.version = function() { return getPackage()["version"]; }
exports.revision = function() { return getPackage()["cappuccino-revision"]; }
exports.timestamp = function() { return new Date(getPackage()["cappuccino-timestamp"]); }
exports.fullVersionString = function() {
return sprintf("cappuccino %s (%04d-%02d-%02d %s)",
exports.version(),
exports.timestamp().getUTCFullYear(),
exports.timestamp().getUTCMonth()+1,
exports.timestamp().getUTCDate(),
exports.revision().slice(0,6)
);
}
@@ -5,6 +5,8 @@ var Context = require("interpreter").Context;
ObjectiveJRuntimeAnalyzer = function(rootPath)
{
this.rootPath = rootPath;
this.rootURL = new CFURL(String(rootPath));
this.context = new Context();
this.scope = setupObjectiveJ(this.context);
@@ -28,6 +30,14 @@ ObjectiveJRuntimeAnalyzer = function(rootPath)
var url = this.executableURL();
return url ? url.absoluteURL().path() : null;
}
var requestedURLs = this.requestedURLs = {};
var _lookupCachedRequest = this.context.global.CFHTTPRequest._lookupCachedRequest;
this.context.global.CFHTTPRequest._lookupCachedRequest = function(aURL) {
var path = new CFURL(aURL, this.rootURL).absoluteURL().path();
requestedURLs[path] = true;
return _lookupCachedRequest.apply(null, arguments);
}
}
ObjectiveJRuntimeAnalyzer.prototype.setIncludePaths = function(includePaths) {
@@ -0,0 +1,57 @@
var URLCache = { };
CFHTTPRequest.prototype.open = function(/*String*/ method, /*String*/ url, /*Boolean*/ async, /*String*/ user, /*String*/ password)
{
var cachedRequest = CFHTTPRequest._lookupCachedRequest(url);
if (cachedRequest)
{
var self = this;
this._nativeRequest = cachedRequest;
this._nativeRequest.onreadystatechange = function()
{
ObjectiveJ.determineAndDispatchHTTPRequestEvents(self);
};
}
return this._nativeRequest.open(method, url, async, user, password);
}
CFHTTPRequest._cacheRequest = function(/*CFURL|String*/ aURL, /*Number*/ status, /*Object*/ headers, /*String*/ body)
{
URLCache[aURL] = new MockXMLHttpRequest(status, headers, body);
}
CFHTTPRequest._lookupCachedRequest = function(/*CFURL|String*/ aURL)
{
return URLCache[aURL];
}
function MockXMLHttpRequest(status, headers, body)
{
this.readyState = CFHTTPRequest.UninitializedState;
this.status = status || 200;
this.statusText = "";
this.responseText = body || "";
this._responseHeaders = headers || {};
};
MockXMLHttpRequest.prototype.open = function(method, url, async, user, password)
{
this.readyState = CFHTTPRequest.LoadingState;
this.async = async;
};
MockXMLHttpRequest.prototype.send = function(body)
{
var self = this;
self.responseText = self.responseText.toString();
function complete() {
for (self.readyState = CFHTTPRequest.LoadedState; self.readyState <= CFHTTPRequest.CompleteState; self.readyState++)
self.onreadystatechange();
}
(self.async ? ObjectiveJ.Asynchronous(complete) : complete)();
};
MockXMLHttpRequest.prototype.onreadystatechange = function() {};
MockXMLHttpRequest.prototype.abort = function() {};
MockXMLHttpRequest.prototype.setRequestHeader = function(header, value) {};
MockXMLHttpRequest.prototype.getAllResponseHeaders = function() { return this._responseHeaders; };
MockXMLHttpRequest.prototype.getResponseHeader = function(header) { return this._responseHeaders[header]; };
MockXMLHttpRequest.prototype.overrideMimeType = function(mimetype) {};
-1
View File
@@ -4,7 +4,6 @@
"description": "Cappuccino module",
"keywords": ["objective-j", "objj", "objective j", "capp", "cappuccino"],
"author": "280 North, Inc. (http://280north.com/)",
"version": "0.8.0",
"objj-frameworks": ["Frameworks"],
"objj-debug-frameworks": ["Frameworks/Debug"],
"contributors": [
+10 -6
View File
@@ -105,7 +105,11 @@
*/
+ (id)alloc
{
return [];
var a = [];
a._retainCount = 1;
a._UID = objj_generateObjectUID();
OBJJ_MEMORY_TABLE[a._UID] = a;
return a;
}
/*!
@@ -113,7 +117,7 @@
*/
+ (id)array
{
return [[self alloc] init];
return [[[self alloc] init] autorelease];
}
/*!
@@ -123,7 +127,7 @@
*/
+ (id)arrayWithArray:(CPArray)anArray
{
return [[self alloc] initWithArray:anArray];
return [[[self alloc] initWithArray:anArray] autorelease];
}
/*!
@@ -133,7 +137,7 @@
*/
+ (id)arrayWithObject:(id)anObject
{
return [[self alloc] initWithObjects:anObject];
return [[[self alloc] initWithObjects:anObject] autorelease];
}
/*!
@@ -150,7 +154,7 @@
for(; i < arguments.length && (argument = arguments[i]) != nil; ++i)
array.push(argument);
return array;
return [array autorelease];
}
/*!
@@ -161,7 +165,7 @@
*/
+ (id)arrayWithObjects:(id)objects count:(unsigned)aCount
{
return [[self alloc] initWithObjects:objects count:aCount];
return [[[self alloc] initWithObjects:objects count:aCount] autorelease];
}
/*!
+56
View File
@@ -0,0 +1,56 @@
@import "CPObject.j"
var MAIN_POOL = nil;
@implementation CPAutoreleasePool : CPObject
{
CPArray _objects;
}
+ (void)initialize
{
MAIN_POOL = [CPAutoreleasePool new];
}
+ (id)_mainAutoreleasePool
{
return MAIN_POOL;
}
+ (void)addObject:(id)anObject
{
[[self _mainAutoreleasePool] addObject:anObject];
}
- (id)init
{
if (self = [super init])
{
_objects = [];
[[CPRunLoop currentRunLoop] performSelector:@selector(drain) target:self argument:nil order:0 modes:[CPDefaultRunLoopMode]];
}
return self;
}
- (void)addObject:(id)anObject
{
_objects.push(anObject);
}
- (void)drain
{
for (var i = 0, count = [_objects count]; i < count; i++)
[_objects.pop() release];
[[CPRunLoop currentRunLoop] performSelector:@selector(drain) target:self argument:nil order:0 modes:[CPDefaultRunLoopMode]];
}
- (void)dealloc
{
[self drain];
[super dealloc];
}
@end
+1 -1
View File
@@ -72,7 +72,7 @@ var CPBundlesForURLStrings = { };
if (self)
{
_bundle = new CFBundle(aURL);
CPBundlesForURLStrings[URLString] = self;
CPBundlesForURLStrings[URLString] = [self retain];
}
return self;
+5 -5
View File
@@ -40,27 +40,27 @@
+ (CPData)data
{
return [[self alloc] init];
return [[[self alloc] init] autorelease];
}
+ (CPData)dataWithRawString:(CPString)aString
{
return [[self alloc] initWithRawString:aString];
return [[[self alloc] initWithRawString:aString] autorelease];
}
+ (CPData)dataWithPlistObject:(id)aPlistObject
{
return [[self alloc] initWithPlistObject:aPlistObject];
return [[[self alloc] initWithPlistObject:aPlistObject] autorelease];
}
+ (CPData)dataWithPlistObject:(id)aPlistObject format:(CPPropertyListFormat)aFormat
{
return [[self alloc] initWithPlistObject:aPlistObject format:aFormat];
return [[[self alloc] initWithPlistObject:aPlistObject format:aFormat] autorelease];
}
+ (CPData)dataWithJSONObject:(Object)anObject
{
return [[self alloc] initWithJSONObject:anObject];
return [[[self alloc] initWithJSONObject:anObject] autorelease];
}
- (id)initWithRawString:(CPString)aString
+19 -13
View File
@@ -24,7 +24,13 @@
@import "CPString.j"
var CPDateReferenceDate = new Date(Date.UTC(2001,1,1,0,0,0,0));
var CPDateReferenceDate = new Date(Date.UTC(2001,1,1,0,0,0,0)),
_CPDateAllocator = function(a) {
a._retainCount = 1;
a._UID = objj_generateObjectUID();
OBJJ_MEMORY_TABLE[a._UID] = a;
return a;
};
/*!
@class CPDate
@@ -39,48 +45,48 @@ var CPDateReferenceDate = new Date(Date.UTC(2001,1,1,0,0,0,0));
+ (id)alloc
{
return new Date;
return _CPDateAllocator(new Date);
}
+ (id)date
{
return [[self alloc] init];
return [[[self alloc] init] autorelease];
}
+ (id)dateWithTimeIntervalSinceNow:(CPTimeInterval)seconds
{
return [[CPDate alloc] initWithTimeIntervalSinceNow:seconds];
return [[[CPDate alloc] initWithTimeIntervalSinceNow:seconds] autorelease];
}
+ (id)dateWithTimeIntervalSince1970:(CPTimeInterval)seconds
{
return [[CPDate alloc] initWithTimeIntervalSince1970:seconds];
return [[[CPDate alloc] initWithTimeIntervalSince1970:seconds] autorelease];
}
+ (id)dateWithTimeIntervalSinceReferenceDate:(CPTimeInterval)seconds
{
return [[CPDate alloc] initWithTimeIntervalSinceReferenceDate:seconds];
return [[[CPDate alloc] initWithTimeIntervalSinceReferenceDate:seconds] autorelease];
}
+ (id)distantPast
{
return new Date(-10000,1,1,0,0,0,0);
return [_CPDateAllocator(new Date(-10000,1,1,0,0,0,0)) autorelease];
}
+ (id)distantFuture
{
return new Date(10000,1,1,0,0,0,0);
return [_CPDateAllocator(new Date(10000,1,1,0,0,0,0)) autorelease];
}
- (id)initWithTimeIntervalSinceNow:(CPTimeInterval)seconds
{
self = new Date((new Date()).getTime() + seconds * 1000);
self = _CPDateAllocator(new Date((new Date()).getTime() + seconds * 1000));
return self;
}
- (id)initWithTimeIntervalSince1970:(CPTimeInterval)seconds
{
self = new Date(seconds * 1000);
self = _CPDateAllocator(new Date(seconds * 1000));
return self;
}
@@ -92,7 +98,7 @@ var CPDateReferenceDate = new Date(Date.UTC(2001,1,1,0,0,0,0));
- (id)initWithTimeInterval:(CPTimeInterval)seconds sinceDate:(CPDate)refDate
{
self = new Date(refDate.getTime() + seconds * 1000);
self = _CPDateAllocator(new Date(refDate.getTime() + seconds * 1000));
return self;
}
@@ -117,7 +123,7 @@ var CPDateReferenceDate = new Date(Date.UTC(2001,1,1,0,0,0,0));
date.setMinutes(d[5]);
date.setSeconds(d[6]);
self = new Date(date.getTime() + (timeZoneOffset - date.getTimezoneOffset()) * 60 * 1000);
self = _CPDateAllocator(new Date(date.getTime() + (timeZoneOffset - date.getTimezoneOffset()) * 60 * 1000));
return self;
}
@@ -185,7 +191,7 @@ var CPDateReferenceDate = new Date(Date.UTC(2001,1,1,0,0,0,0));
- (id)copy
{
return new Date(self.getTime());
return _CPDateAllocator(new Date(self.getTime()));
}
@end
+18 -7
View File
@@ -92,7 +92,7 @@
*/
+ (id)dictionary
{
return [[self alloc] init];
return [[[self alloc] init] autorelease];;
}
/*!
@@ -102,7 +102,7 @@
*/
+ (id)dictionaryWithDictionary:(CPDictionary)aDictionary
{
return [[self alloc] initWithDictionary:aDictionary];
return [[[self alloc] initWithDictionary:aDictionary] autorelease];
}
/*!
@@ -113,7 +113,7 @@
*/
+ (id)dictionaryWithObject:(id)anObject forKey:(id)aKey
{
return [[self alloc] initWithObjects:[anObject] forKeys:[aKey]];
return [[[self alloc] initWithObjects:[anObject] forKeys:[aKey]] autorelease];
}
/*!
@@ -125,7 +125,7 @@
*/
+ (id)dictionaryWithObjects:(CPArray)objects forKeys:(CPArray)keys
{
return [[self alloc] initWithObjects:objects forKeys:keys];
return [[[self alloc] initWithObjects:objects forKeys:keys] autorelease];
}
/*!
@@ -135,7 +135,7 @@
*/
+ (id)dictionaryWithJSObject:(JSObject)object
{
return [self dictionaryWithJSObject:object recursively:NO];
return [[self dictionaryWithJSObject:object recursively:NO] autorelease];
}
/*!
@@ -145,7 +145,7 @@
*/
+ (id)dictionaryWithJSObject:(JSObject)object recursively:(BOOL)recursively
{
var dictionary = [[self alloc] init];
var dictionary = [[[self alloc] init] autorelease];
for (var key in object)
{
@@ -153,6 +153,12 @@
continue;
var value = object[key];
if (value === null)
{
[dictionary setObject:[CPNull null] forKey:key];
continue;
}
if (recursively)
{
@@ -203,7 +209,7 @@
arguments[0] = [self alloc];
arguments[1] = @selector(initWithObjectsAndKeys:);
return objj_msgSend.apply(this, arguments);
return [objj_msgSend.apply(this, arguments) autorelease];
}
/*!
@@ -521,6 +527,11 @@
return self.toString();
}
- (BOOL)containsKey:(id)aKey
{
var value = [self objectForKey:aKey];
return ((value !== nil) && (value !== undefined));
}
@end
@implementation CPDictionary (CPCoding)
+6 -3
View File
@@ -47,7 +47,7 @@
*/
+ (id)indexSet
{
return [[self alloc] init];
return [[[self alloc] init] autorelease];
}
/*!
@@ -55,7 +55,7 @@
*/
+ (id)indexSetWithIndex:(int)anIndex
{
return [[self alloc] initWithIndex:anIndex];
return [[[self alloc] initWithIndex:anIndex] autorelease];
}
/*!
@@ -64,7 +64,7 @@
*/
+ (id)indexSetWithIndexesInRange:(CPRange)aRange
{
return [[self alloc] initWithIndexesInRange:aRange];
return [[[self alloc] initWithIndexesInRange:aRange] autorelease];
}
// Initializing and Index Set
@@ -739,7 +739,10 @@
shifts = [];
for (; j < count; ++j)
{
[shifts addObject:_ranges[j]];
_count -= _ranges[j].length;
}
if ((j = i + 1) < count)
{
+1 -1
View File
@@ -46,7 +46,7 @@
*/
+ (id)invocationWithMethodSignature:(CPMethodSignature)aMethodSignature
{
return [[self alloc] initWithMethodSignature:aMethodSignature];
return [[[self alloc] initWithMethodSignature:aMethodSignature] autorelease];
}
/*!
+1 -1
View File
@@ -56,7 +56,7 @@ CPJSONPCallbackReplacementString = @"${JSONP_CALLBACK}";
+ (CPJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate
{
return [[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate startImmediately:YES];;
return [[[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate startImmediately:YES] autorelease];
}
- (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate
+9
View File
@@ -277,5 +277,14 @@ CPUnknownUserInfoKey = @"CPUnknownUserInfoKey";
@end
@implementation CPNull (KeyValueCoding)
- (id)valueForKey:(CPString)aKey
{
return self;
}
@end
@import "CPKeyValueObserving.j"
@import "CPArray+KVO.j"
+1 -1
View File
@@ -148,7 +148,7 @@ var _CPKeyedArchiverStringClass = Nil,
+ (CPData)archivedDataWithRootObject:(id)anObject
{
var data = [CPData dataWithPlistObject:nil],
archiver = [[self alloc] initForWritingWithMutableData:data];
archiver = [[[self alloc] initForWritingWithMutableData:data] autorelease];
[archiver encodeObject:anObject forKey:@"root"];
[archiver finishEncoding];
+12 -6
View File
@@ -163,9 +163,15 @@ var CPArrayClass = Ni
@param data the data from which to read the graph
@return the unarchived object
*/
+ (id)unarchiveObjectWithData:(CPData)data
+ (id)unarchiveObjectWithData:(CPData)aData
{
var unarchiver = [[self alloc] initForReadingWithData:data],
if (!aData)
{
CPLog.error("Null data passed to -[CPKeyedUnarchiver unarchiveObjectWithData:].");
return nil;
}
var unarchiver = [[[self alloc] initForReadingWithData:aData] autorelease],
object = [unarchiver decodeObjectForKey:@"root"];
[unarchiver finishDecoding];
@@ -200,7 +206,7 @@ var CPArrayClass = Ni
- (CPDictionary)_decodeDictionaryOfObjectsForKey:(CPString)aKey
{
var object = _plistObject.valueForKey(aKey),
objectClass = object && object.isa;
objectClass = (object != nil) && object.isa;
if (objectClass === CPDictionaryClass || objectClass === CPMutableDictionaryClass)
{
@@ -315,7 +321,7 @@ var CPArrayClass = Ni
- (id)decodeObjectForKey:(CPString)aKey
{
var object = _plistObject.valueForKey(aKey),
objectClass = object && object.isa;
objectClass = (object != nil) && object.isa;
if (objectClass === CPDictionaryClass || objectClass === CPMutableDictionaryClass)
return _CPKeyedUnarchiverDecodeObjectAtIndex(self, object.valueForKey(_CPKeyedArchiverUIDKey));
@@ -465,7 +471,7 @@ var _CPKeyedUnarchiverDecodeObjectAtIndex = function(self, anIndex)
self._plistObject = savedPlistObject;
if (processedObject != object)
if (processedObject !== object)
{
if (self._delegateSelectors & _CPKeyedUnarchiverWillReplaceObjectWithObjectSelector)
[self._delegate unarchiver:self willReplaceObject:object withObject:processedObject];
@@ -519,7 +525,7 @@ var _CPKeyedUnarchiverDecodeObjectAtIndex = function(self, anIndex)
// If this object is a member of _CPKeyedArchiverValue, then we know
// that it is a wrapper for a primitive JavaScript object.
if (object.isa === _CPKeyedArchiverValueClass)
if ((object != nil) && (object.isa === _CPKeyedArchiverValueClass))
object = [object JSObject];
return object;
+2 -2
View File
@@ -53,7 +53,7 @@
*/
+ (CPNotification)notificationWithName:(CPString)aNotificationName object:(id)anObject userInfo:(CPDictionary)aUserInfo
{
return [[self alloc] initWithName:aNotificationName object:anObject userInfo:aUserInfo];
return [[[self alloc] initWithName:aNotificationName object:anObject userInfo:aUserInfo] autorelease];
}
/*!
@@ -64,7 +64,7 @@
*/
+ (CPNotification)notificationWithName:(CPString)aNotificationName object:(id)anObject
{
return [[self alloc] initWithName:aNotificationName object:anObject userInfo:nil];
return [[[self alloc] initWithName:aNotificationName object:anObject userInfo:nil] autorelease];
}
/*!
+3
View File
@@ -333,4 +333,7 @@ FIXME: Do we need this?
Number.prototype.isa = CPNumber;
Boolean.prototype.isa = CPNumber;
Number.prototype._retainCount = Infinity;
Boolean.prototype._retainCount = Infinity;
[CPNumber initialize];
+10 -1
View File
@@ -89,7 +89,6 @@ CPLog(@"Got some class: %@", inst);
*/
+ (id)alloc
{
// CPLog("calling alloc on " + self.name + ".");
return class_createInstance(self);
}
@@ -130,6 +129,7 @@ CPLog(@"Got some class: %@", inst);
*/
- (void)dealloc
{
delete OBJJ_MEMORY_TABLE[[self UID]];
}
// Identifying classes
@@ -464,6 +464,7 @@ CPLog(@"Got some class: %@", inst);
*/
- (id)autorelease
{
[CPAutoreleasePool addObject:self];
return self;
}
@@ -498,6 +499,7 @@ CPLog(@"Got some class: %@", inst);
*/
- (id)retain
{
_retainCount++;
return self;
}
@@ -506,6 +508,11 @@ CPLog(@"Got some class: %@", inst);
*/
- (void)release
{
_retainCount--;
if (_retainCount === 0)
[self dealloc];
else if (OBJJ_ZOMBIE_DETECTION && _retainCount < 0)
throw ("Released a zombie object: "+self);
}
/*!
@@ -535,3 +542,5 @@ objj_class.prototype.toString = objj_object.prototype.toString = function()
else
return String(this) + " (-description not implemented)";
}
@import "CPAutoreleasePool.j"
+1 -1
View File
@@ -61,7 +61,7 @@
- (void)forwardInvocation:(CPInvocation)anInvocation
{
[CPException raise:CPInvalidArgumentException
reason:@"-methodSignatureForSelector: called on abstract CPProxy class."];
reason:@"-forwardInvocation: called on abstract CPProxy class."];
}
// FIXME: This should be moved to the runtime?
+1 -1
View File
@@ -73,7 +73,7 @@ var _CPRunLoopPerformPool = [],
return perform;
}
return [[self alloc] initWithSelector:aSelector target:aTarget argument:anArgument order:anOrder modes:modes];
return [[[self alloc] initWithSelector:aSelector target:aTarget argument:anArgument order:anOrder modes:modes] autorelease];
}
- (id)initWithSelector:(SEL)aSelector target:(SEL)aTarget argument:(id)anArgument order:(unsigned)anOrder modes:(CPArray)modes
+6 -6
View File
@@ -45,7 +45,7 @@
*/
+ (id)set
{
return [[self alloc] init];
return [[[self alloc] init] autorelease];
}
/*
@@ -54,7 +54,7 @@
*/
+ (id)setWithArray:(CPArray)array
{
return [[self alloc] initWithArray:array];
return [[[self alloc] initWithArray:array] autorelease];
}
/*
@@ -63,7 +63,7 @@
*/
+ (id)setWithObject:(id)anObject
{
return [[self alloc] initWithArray:[anObject]];
return [[[self alloc] initWithArray:[anObject]] autorelease];
}
/*
@@ -73,7 +73,7 @@
*/
+ (id)setWithObjects:(id)objects count:(unsigned)count
{
return [[self alloc] initWithObjects:objects count:count];
return [[[self alloc] initWithObjects:objects count:count] autorelease];
}
/*
@@ -90,7 +90,7 @@
for(; i < argLength && ((argument = arguments[i]) !== nil); ++i)
[set addObject:argument];
return set;
return [set autorelease];
}
/*
@@ -99,7 +99,7 @@
*/
+ (id)setWithSet:(CPSet)set
{
return [[self alloc] initWithSet:set];
return [[[self alloc] initWithSet:set] autorelease];
}
/*
+1 -1
View File
@@ -78,7 +78,7 @@ CPOrderedDescending = 1;
+ (id)sortDescriptorWithKey:(CPString)aKey ascending:(BOOL)isAscending selector:(SEL)aSelector
{
return [[self alloc] initWithKey:aKey ascending:isAscending selector:aSelector];
return [[[self alloc] initWithKey:aKey ascending:isAscending selector:aSelector] autorelease];
}
/*!
+19
View File
@@ -664,6 +664,9 @@ var CPStringRegexSpecialCharacters = [
*/
- (CPString)pathExtension
{
if (lastIndexOf('.') === CPNotFound)
return "";
return substr(lastIndexOf('.') + 1);
}
@@ -699,6 +702,21 @@ var CPStringRegexSpecialCharacters = [
return path;
}
/*!
Deletes the extension of a string.
*/
- (CPString)stringByDeletingPathExtension
{
var extension = [self pathExtension];
if (extension === "")
return self;
if (lastIndexOf('.') < 1)
return self;
return substr(0, [self length] - (extension.length + 1));
}
- (CPString)stringByStandardizingPath
{
return objj_standardize_path(self);
@@ -751,3 +769,4 @@ var CPStringRegexSpecialCharacters = [
@end
String.prototype.isa = CPString;
String.prototype._retainCount = Infinity;
+6 -6
View File
@@ -48,7 +48,7 @@
*/
+ (CPTimer)scheduledTimerWithTimeInterval:(CPTimeInterval)seconds invocation:(CPInvocation)anInvocation repeats:(BOOL)shouldRepeat
{
var timer = [[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds invocation:anInvocation repeats:shouldRepeat];
var timer = [[[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds invocation:anInvocation repeats:shouldRepeat] autorelease];
//add to the runloop
[[CPRunLoop currentRunLoop] addTimer:timer forMode:CPDefaultRunLoopMode];
@@ -61,7 +61,7 @@
*/
+ (CPTimer)scheduledTimerWithTimeInterval:(CPTimeInterval)seconds target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)shouldRepeat
{
var timer = [[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds target:aTarget selector:aSelector userInfo:userInfo repeats:shouldRepeat]
var timer = [[[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds target:aTarget selector:aSelector userInfo:userInfo repeats:shouldRepeat] autorelease];
//add to the runloop
[[CPRunLoop currentRunLoop] addTimer:timer forMode:CPDefaultRunLoopMode];
@@ -74,7 +74,7 @@
*/
+ (CPTimer)scheduledTimerWithTimeInterval:(CPTimeInterval)seconds callback:(Function)aFunction repeats:(BOOL)shouldRepeat
{
var timer = [[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds callback:aFunction repeats:shouldRepeat];
var timer = [[[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds callback:aFunction repeats:shouldRepeat] autorelease];
//add to the runloop
[[CPRunLoop currentRunLoop] addTimer:timer forMode:CPDefaultRunLoopMode];
@@ -87,7 +87,7 @@
*/
+ (CPTimer)timerWithTimeInterval:(CPTimeInterval)seconds invocation:(CPInvocation)anInvocation repeats:(BOOL)shouldRepeat
{
return [[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds invocation:anInvocation repeats:shouldRepeat];
return [[[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds invocation:anInvocation repeats:shouldRepeat] autorelease];
}
/*!
@@ -95,7 +95,7 @@
*/
+ (CPTimer)timerWithTimeInterval:(CPTimeInterval)seconds target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)shouldRepeat
{
return [[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds target:aTarget selector:aSelector userInfo:userInfo repeats:shouldRepeat];
return [[[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds target:aTarget selector:aSelector userInfo:userInfo repeats:shouldRepeat] autorelease];
}
/*!
@@ -103,7 +103,7 @@
*/
+ (CPTimer)timerWithTimeInterval:(CPTimeInterval)seconds callback:(Function)aFunction repeats:(BOOL)shouldRepeat
{
return [[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds callback:aFunction repeats:shouldRepeat];
return [[[self alloc] initWithFireDate:[CPDate dateWithTimeIntervalSinceNow:seconds] interval:seconds callback:aFunction repeats:shouldRepeat] autorelease];
}
/*!
+3 -3
View File
@@ -55,7 +55,7 @@ CPURLCustomIconKey = @"CPURLCustomIconKey";
+ (id)URLWithString:(CPString)URLString
{
return [[self alloc] initWithString:URLString];
return [[[self alloc] initWithString:URLString] autorelease];
}
- (id)initWithString:(CPString)URLString relativeToURL:(CPURL)aBaseURL
@@ -196,8 +196,8 @@ var CPURLURLStringKey = @"CPURLURLStringKey",
- (id)initWithCoder:(CPCoder)aCoder
{
return [self initWithURLString:[aCoder decodeObjectForKey:CPURLURLStringKey]
baseURL:[aCoder decodeObjectForKey:CPURLBaseURLKey]];
return [self initWithString:[aCoder decodeObjectForKey:CPURLURLStringKey]
relativeToURL:[aCoder decodeObjectForKey:CPURLBaseURLKey]];
}
- (void)encodeWithCoder:(CPCoder)aCoder
+1 -1
View File
@@ -128,7 +128,7 @@ var CPURLConnectionDelegate = nil;
*/
+ (CPURLConnection)connectionWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate
{
return [[self alloc] initWithRequest:aRequest delegate:aDelegate];
return [[[self alloc] initWithRequest:aRequest delegate:aDelegate] autorelease];
}
/*
+1 -1
View File
@@ -48,7 +48,7 @@
*/
+ (id)requestWithURL:(CPURL)aURL
{
return [[CPURLRequest alloc] initWithURL:aURL];
return [[[CPURLRequest alloc] initWithURL:aURL] autorelease];
}
/*!
+1 -1
View File
@@ -71,7 +71,7 @@ var _CPUndoGroupingPool = [],
return grouping;
}
return [[self alloc] initWithParent:anUndoGrouping];
return [[[self alloc] initWithParent:anUndoGrouping] autorelease];
}
- (id)initWithParent:(_CPUndoGrouping)anUndoGrouping
+1 -1
View File
@@ -43,7 +43,7 @@
*/
+ (id)valueWithJSObject:(JSObject)aJSObject
{
return [[self alloc] initWithJSObject:aJSObject];
return [[[self alloc] initWithJSObject:aJSObject] autorelease];
}
/*!
+1
View File
@@ -20,6 +20,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import "CPAutoreleasePool.j"
@import "CPArray.j"
@import "CPBundle.j"
@import "CPCoder.j"
+1 -1
View File
@@ -34,7 +34,7 @@ foundationTask = framework ("Foundation", function(foundationTask)
foundationTask.setEmail("feedback @nospam@ 280north.com");
foundationTask.setSummary("Foundation classes for Cappuccino");
foundationTask.setIdentifier("com.280n.Foundation");
foundationTask.setVersion("0.8.0");
foundationTask.setVersion(getCappuccinoVersion());
foundationTask.setLicense(BundleTask.License.LGPL_v2_1);
foundationTask.setSources(new FileList("**/*.j"));
foundationTask.setResources(new FileList("Resources/**/*"));
+31 -19
View File
@@ -247,7 +247,7 @@ task ("demos", function()
// Testing
task("test", ["build", "test-only"]);
task("test", ["CommonJS", "test-only"]);
task("test-only", function()
{
@@ -280,21 +280,23 @@ task("push-objective-j", function() {
function pushPackage(path, remote, branch)
{
branch = branch || "master";
var pushPackagesPath = FILE.path(".push-package");
pushPackagesPath.mkdirs();
var packagePath = pushPackagesPath.join(remote.replace(/[^\w]/g, "_"));
stream.print("Pushing \0blue(" + path + "\0) to "+branch+" of \0blue(" + remote + "\0)");
FILE.mkdirs(".push-package");
var pushPackageDir = FILE.join(".push-package", remote.replace(/[^\w]/g, "_"));
if (FILE.exists(pushPackageDir))
OS.system(buildCmd([["cd", pushPackageDir], ["git", "fetch"]]));
if (packagePath.isDirectory())
OS.system(buildCmd([["cd", packagePath], ["git", "fetch"]]));
else
OS.system(["git", "clone", remote, pushPackageDir]);
OS.system(["git", "clone", remote, packagePath]);
if (OS.system(buildCmd([["cd", pushPackageDir], ["git", "checkout", "origin/"+branch]]))) {
if (OS.system(buildCmd([["cd", packagePath], ["git", "checkout", "origin/"+branch]]))) {
if (OS.system(buildCmd([
["cd", pushPackageDir],
["cd", packagePath],
["git", "symbolic-ref", "HEAD", "refs/heads/"+branch],
["rm", ".git/index"],
["git", "clean", "-fdx"]
@@ -302,20 +304,30 @@ function pushPackage(path, remote, branch)
throw "pushPackage failed";
}
if (OS.system("cd "+OS.enquote(pushPackageDir)+" && git rm --ignore-unmatch -r * && rm -rf *"))
if (OS.system("cd "+OS.enquote(packagePath)+" && git rm --ignore-unmatch -r * && rm -rf *"))
throw "pushPackage failed";
if (OS.system("cp -R "+OS.enquote(path)+"/* "+OS.enquote(pushPackageDir)+"/."))
if (OS.system("cp -R "+OS.enquote(path)+"/* "+OS.enquote(packagePath)+"/."))
throw "pushPackage failed";
OS.system(buildCmd([
["cd", pushPackageDir],
var pkg = JSON.parse(packagePath.join("package.json").read({ charset : "UTF-8" }));
stream.print(" Version: \0purple(" + pkg["version"] + "\0)");
stream.print(" Revision: \0purple(" + pkg["cappuccino-revision"] + "\0)");
stream.print(" Timestamp: \0purple(" + pkg["cappuccino-timestamp"] + "\0)");
var cmd = [
["cd", packagePath],
["git", "add", "."],
["git", "commit", "-m", "Pushed on " + new Date()]
]));
["git", "commit", "-m", "version="+pkg.version+"; revision="+pkg["cappuccino-revision"]+"; timestamp="+pkg["cappuccino-timestamp"]+";"]
];
if (pkg["cappuccino-revision"])
cmd.push(["git", "tag", "rev-"+pkg["cappuccino-revision"].slice(0,6)]);
OS.system(buildCmd(cmd));
if (OS.system(buildCmd([
["cd", pushPackageDir],
["git", "push", "origin", "HEAD:"+branch]
["cd", packagePath],
["git", "push", "--tags", "origin", "HEAD:"+branch]
])))
throw "pushPackage failed";
}
+30 -1
View File
@@ -81,7 +81,36 @@ function resolveMainBundleURL()
Executable.fileImporterForURL(mainBundleURL)(mainFileURL.lastPathComponent(), YES, function()
{
disableCFURLCaching();
afterDocumentLoad(main);
afterDocumentLoad(function()
{
var hashString = window.location.hash.substring(1),
args = [];
if (hashString.length)
{
args = hashString.split("/");
for (var i = 0, count = args.length; i < count; i++)
args[i] = decodeURIComponent(args[i]);
}
var namedArgsArray = window.location.search.substring(1).split("&"),
namedArgs = new CFMutableDictionary();
for (var i = 0, count = namedArgsArray.length; i < count; i++)
{
var thisArg = namedArgsArray[i].split("=");
if (!thisArg[0])
continue;
if (thisArg[1] == null)
thisArg[1] = true;
namedArgs.setValueForKey(decodeURIComponent(thisArg[0]), decodeURIComponent(thisArg[1]));
}
main(args, namedArgs);
});
});
});
}
+66 -8
View File
@@ -49,6 +49,7 @@ GLOBAL(CFBundle) = function(/*CFURL|String*/ aURL)
this._resourcesDirectoryURL = new CFURL("Resources/", aURL);
this._staticResource = NULL;
this._isValid = NO;
this._loadStatus = CFBundleUnloaded;
this._loadRequests = [];
@@ -56,36 +57,53 @@ GLOBAL(CFBundle) = function(/*CFURL|String*/ aURL)
this._infoDictionary = new CFDictionary();
this._eventDispatcher = new EventDispatcher(this);
this._UID = objj_generateObjectUID();
this._retainCount = 1;
OBJJ_MEMORY_TABLE[this._UID] = this;
}
DISPLAY_NAME(CFBundle);
CFBundle.environments = function()
{
// Passed in by GCC.
return ENVIRONMENTS;
}
DISPLAY_NAME(CFBundle.environments);
CFBundle.bundleContainingURL = function(/*CFURL|String*/ aURL)
{
aURL = new CFURL(".", makeAbsoluteURL(aURL));
while (aURL.path() !== "/")
{
var bundle = CFBundlesForURLStrings[aURL.absoluteString()];
var previousURLString,
URLString = aURL.absoluteString();
if (bundle)
while (!previousURLString || previousURLString !== URLString)
{
var bundle = CFBundlesForURLStrings[URLString];
if (bundle && bundle._isValid)
return bundle;
aURL = new CFURL("..", aURL);
previousURLString = URLString;
URLString = aURL.absoluteString();
}
return NULL;
}
DISPLAY_NAME(CFBundle.bundleContainingURL);
CFBundle.mainBundle = function()
{
return new CFBundle(mainBundleURL);
}
DISPLAY_NAME(CFBundle.mainBundle);
function addClassToBundle(aClass, aBundle)
{
if (aBundle)
@@ -97,16 +115,22 @@ CFBundle.bundleForClass = function(/*Class*/ aClass)
return CFBundlesForClasses[aClass.name] || CFBundle.mainBundle();
}
DISPLAY_NAME(CFBundle.bundleForClass);
CFBundle.prototype.bundleURL = function()
{
return this._bundleURL;
}
DISPLAY_NAME(CFBundle.prototype.bundleURL);
CFBundle.prototype.resourcesDirectoryURL = function()
{
return this._resourcesDirectoryURL;
}
DISPLAY_NAME(CFBundle.prototype.resourcesDirectoryURL);
CFBundle.prototype.resourceURL = function(/*String*/ aResourceName, /*String*/ aType, /*String*/ aSubDirectory)
{
if (aType)
@@ -120,6 +144,8 @@ CFBundle.prototype.resourceURL = function(/*String*/ aResourceName, /*String*/ a
return resourceURL.absoluteURL();
}
DISPLAY_NAME(CFBundle.prototype.resourceURL);
CFBundle.prototype.mostEligibleEnvironmentURL = function()
{
if (this._mostEligibleEnvironmentURL === undefined)
@@ -128,6 +154,8 @@ CFBundle.prototype.mostEligibleEnvironmentURL = function()
return this._mostEligibleEnvironmentURL;
}
DISPLAY_NAME(CFBundle.prototype.mostEligibleEnvironmentURL);
CFBundle.prototype.executableURL = function()
{
if (this._executableURL === undefined)
@@ -143,16 +171,22 @@ CFBundle.prototype.executableURL = function()
return this._executableURL;
}
DISPLAY_NAME(CFBundle.prototype.executableURL);
CFBundle.prototype.infoDictionary = function()
{
return this._infoDictionary;
}
DISPLAY_NAME(CFBundle.prototype.infoDictionary);
CFBundle.prototype.valueForInfoDictionaryKey = function(/*String*/ aKey)
{
return this._infoDictionary.valueForKey(aKey);
}
DISPLAY_NAME(CFBundle.prototype.valueForInfoDictionaryKey);
CFBundle.prototype.hasSpritedImages = function()
{
var environments = this._infoDictionary.valueForKey("CPBundleEnvironmentsWithImageSprites") || [],
@@ -166,11 +200,15 @@ CFBundle.prototype.hasSpritedImages = function()
return NO;
}
DISPLAY_NAME(CFBundle.prototype.hasSpritedImages);
CFBundle.prototype.environments = function()
{
return this._infoDictionary.valueForKey("CPBundleEnvironments") || ["ObjJ"];
}
DISPLAY_NAME(CFBundle.prototype.environments);
CFBundle.prototype.mostEligibleEnvironment = function(/*Array*/ environments)
{
environments = environments || this.environments();
@@ -194,11 +232,15 @@ CFBundle.prototype.mostEligibleEnvironment = function(/*Array*/ environments)
return NULL;
}
DISPLAY_NAME(CFBundle.prototype.mostEligibleEnvironment);
CFBundle.prototype.isLoading = function()
{
return this._loadStatus & CFBundleLoading;
}
DISPLAY_NAME(CFBundle.prototype.isLoading);
CFBundle.prototype.load = function(/*BOOL*/ shouldExecute)
{
if (this._loadStatus !== CFBundleUnloaded)
@@ -223,7 +265,13 @@ CFBundle.prototype.load = function(/*BOOL*/ shouldExecute)
function onsuccess(/*Event*/ anEvent)
{
self._loadStatus &= ~CFBundleLoadingInfoPlist;
self._infoDictionary = anEvent.request.responsePropertyList();
var infoDictionary = anEvent.request.responsePropertyList();
self._isValid = !!infoDictionary || CFBundle.mainBundle() === self;
if (infoDictionary)
self._infoDictionary = infoDictionary;
if (!self._infoDictionary)
{
@@ -240,6 +288,7 @@ CFBundle.prototype.load = function(/*BOOL*/ shouldExecute)
function onfailure()
{
self._isValid = CFBundle.mainBundle() === self;
self._loadStatus = CFBundleUnloaded;
finishBundleLoadingWithError(self, new Error("Could not load bundle at \"" + self.bundleURL() + "\""));
@@ -249,6 +298,8 @@ CFBundle.prototype.load = function(/*BOOL*/ shouldExecute)
});
}
DISPLAY_NAME(CFBundle.prototype.load);
function finishBundleLoadingWithError(/*CFBundle*/ aBundle, /*Event*/ anError)
{
resolveStaticResource(aBundle._staticResource);
@@ -390,12 +441,13 @@ function loadSpritedImagesForBundle(/*Bundle*/ aBundle, success, failure)
CFTotalBytesLoaded += anEvent.request.responseText().length;
decompileStaticFile(aBundle, anEvent.request.responseText(), spritedImagesURL);
aBundle._loadStatus &= ~CFBundleLoadingSpritedImages;
success();
}
catch(anException)
{
failure(anException);
}
success();
}, failure);
}
@@ -514,11 +566,11 @@ function executeBundle(/*Bundle*/ aBundle, /*Function*/ aCallback)
else
{
executable.addEventListener("dependenciesload", function()
executable.loadFileDependencies(function()
{
executeStaticResources(index);
});
executable.loadFileDependencies();
return;
}
}
@@ -615,16 +667,22 @@ CFBundle.prototype.addEventListener = function(/*String*/ anEventName, /*Functio
this._eventDispatcher.addEventListener(anEventName, anEventListener);
}
DISPLAY_NAME(CFBundle.prototype.addEventListener);
CFBundle.prototype.removeEventListener = function(/*String*/ anEventName, /*Function*/ anEventListener)
{
this._eventDispatcher.removeEventListener(anEventName, anEventListener);
}
DISPLAY_NAME(CFBundle.prototype.removeEventListener);
CFBundle.prototype.onerror = function(/*Event*/ anEvent)
{
throw anEvent.error;
}
DISPLAY_NAME(CFBundle.prototype.onerror);
CFBundle.prototype.bundlePath = function()
{
return this._bundleURL.absoluteURL().path();
+4
View File
@@ -31,6 +31,10 @@ GLOBAL(CFData) = function()
this._bytes = NULL;
this._base64 = NULL;
this._UID = objj_generateObjectUID();
this._retainCount = 1;
OBJJ_MEMORY_TABLE[this._UID] = this;
}
CFData.prototype.propertyList = function()
+2
View File
@@ -26,6 +26,8 @@ GLOBAL(CFDictionary) = function(/*CFDictionary*/ aDictionary)
this._count = 0;
this._buckets = { };
this._UID = objj_generateObjectUID();
this._retainCount = 1;
OBJJ_MEMORY_TABLE[this._UID] = this;
}
var indexOf = Array.prototype.indexOf,
+22 -33
View File
@@ -196,9 +196,9 @@ CFHTTPRequest.prototype.overrideMimeType = function(/*String*/ aMimeType)
return this._nativeRequest.overrideMimeType(aMimeType);
}
CFHTTPRequest.prototype.open = function(/*...*/)
CFHTTPRequest.prototype.open = function(/*String*/ aMethod, /*String*/ aURL, /*Boolean*/ isAsynchronous, /*String*/ aUser, /*String*/ aPassword)
{
return this._nativeRequest.open(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
return this._nativeRequest.open(aMethod, aURL, isAsynchronous, aUser, aPassword);
}
CFHTTPRequest.prototype.send = function(/*Object*/ aBody)
@@ -254,43 +254,32 @@ function determineAndDispatchHTTPRequestEvents(/*CFHTTPRequest*/ aRequest)
function FileRequest(/*CFURL*/ aURL, onsuccess, onfailure)
{
#ifdef BROWSER
var request = new CFHTTPRequest();
request.onsuccess = Asynchronous(onsuccess);
request.onfailure = Asynchronous(onfailure);
if (aURL.pathExtension() === "plist")
request.overrideMimeType("text/xml");
request.open("GET", aURL.absoluteString(), YES);
if (exports.asyncLoader)
{
request.onsuccess = Asynchronous(onsuccess);
request.onfailure = Asynchronous(onfailure);
}
else
{
request.onsuccess = onsuccess;
request.onfailure = onfailure;
}
request.open("GET", aURL.absoluteString(), exports.asyncLoader);
request.send("");
}
#ifdef BROWSER
exports.asyncLoader = YES;
#else
var FILE = require("file"),
filePath = aURL.absoluteURL().path();
if (!FILE.exists(filePath))
return onfailure();
this._responseText = FILE.read(filePath, { charset:"UTF-8" });
onsuccess({ type:"success", request:this });
exports.asyncLoader = NO;
#endif
}
#ifdef COMMONJS
FileRequest.prototype.responseText = function()
{
return this._responseText;
}
FileRequest.prototype.responseXML = function()
{
return new DOMParser().parseFromString(anXMLString, "text/xml");
}
FileRequest.prototype.responsePropertyList = function()
{
return CFPropertyList.propertyListFromString(this.responseText());
}
#endif
// FIXME: Get rid of these when we no longer need Mock requests in flatten.
exports.Asynchronous = Asynchronous;
exports.determineAndDispatchHTTPRequestEvents = determineAndDispatchHTTPRequestEvents;
+27 -7
View File
@@ -199,6 +199,8 @@ GLOBAL(CFURL) = function(/*CFURL|String*/ aURL, /*CFURL*/ aBaseURL)
}
this._UID = objj_generateObjectUID();
this._retainCount = 1;
OBJJ_MEMORY_TABLE[this._UID] = this;
this._string = aURL;
this._baseURL = aBaseURL;
@@ -314,7 +316,7 @@ function resolveURL(aURL)
resolvedPathComponents.splice(basePathComponents.length - 1, 1);
// If this doesn't start with a "..", then we're simply appending to already standardized paths.
if (pathComponents.length && pathComponents[0] === "..")
if (pathComponents.length && (pathComponents[0] === ".." || pathComponents[0] === "."))
standardizePathComponents(resolvedPathComponents, YES);
resolvedParts.pathComponents = resolvedPathComponents;
@@ -352,19 +354,26 @@ function standardizePathComponents(/*Array*/ pathComponents, /*BOOL*/ inPlace)
var index = 0,
resultIndex = 0,
count = pathComponents.length,
result = inPlace ? pathComponents : [];
result = inPlace ? pathComponents : [],
startsWithPeriod = NO;
for (; index < count; ++index)
{
var component = pathComponents[index];
if (component === "" || component === ".")
if (component === "")
continue;
if (component === ".")
{
startsWithPeriod = resultIndex === 0;
continue;
}
if (component !== ".." || resultIndex === 0 || result[resultIndex - 1] === "..")
{
//if (resultIndex !== index)
result[resultIndex] = component;
result[resultIndex] = component;
resultIndex++;
@@ -375,6 +384,9 @@ function standardizePathComponents(/*Array*/ pathComponents, /*BOOL*/ inPlace)
--resultIndex;
}
if (startsWithPeriod && resultIndex === 0)
result[resultIndex++] = ".";
result.length = resultIndex;
return result;
@@ -505,10 +517,11 @@ CFURL.prototype.hasDirectoryPath = function()
var lastPathComponent = this.lastPathComponent();
hasDirectoryPath = lastPathComponent === "." || lastPathComponent === "..";
this._hasDirectoryPath = hasDirectoryPath;
}
return this._hasDirectoryPath;
return hasDirectoryPath;
}
DISPLAY_NAME(CFURL.prototype.hasDirectoryPath);
@@ -646,7 +659,14 @@ CFURL.prototype.asDirectoryPathURL = function()
if (this.hasDirectoryPath())
return this;
return new CFURL(this.lastPathComponent() + "/", this);
var lastPathComponent = this.lastPathComponent();
// We do this because on Windows the path may start with C: and be
// misinterpreted as a scheme.
if (lastPathComponent !== "/")
lastPathComponent = "./" + lastPathComponent;
return new CFURL(lastPathComponent + "/", this);
}
DISPLAY_NAME(CFURL.prototype.asDirectoryPathURL);
+7
View File
@@ -357,3 +357,10 @@ function _CPLogInitPopup(logWindow)
}, false);
}
#endif
#if COMMONJS
CPLogDefault = CPLogPrint;
#else
CPLogDefault = (typeof window === "object" && window.console) ? CPLogConsole : CPLogPopup;
#endif
+31 -27
View File
@@ -1,5 +1,7 @@
var FILE = require("file");
var sprintf = require("printf").sprintf;
var window = exports.window = require("browser/window");
if (system.engine === "rhino")
@@ -7,7 +9,7 @@ if (system.engine === "rhino")
window.__parent__ = null;
window.__proto__ = global;
}
// setup OBJJ_HOME, OBJJ_INCLUDE_PATHS, etc
window.OBJJ_HOME = exports.OBJJ_HOME = FILE.resolve(module.path, "..");
@@ -77,6 +79,12 @@ exports.run = function(args)
// copy the args since we're going to modify them
var argv = args.slice(1);
if (argv[0] === "--version")
{
print(exports.fullVersionString());
return;
}
while (argv.length && argv[0].indexOf('-I') === 0)
OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, argv.shift().substr(2).split(':'));
}
@@ -140,37 +148,12 @@ exports.repl = function()
}
}
exports.objj_eval = function(/*String*/ aString)
{
// We need this while code still refers to window.
Executable.setCommonJSArguments(require, exports, module, system, print, window);
var executable = exports.preprocess(aString, "", 0);
if (!executable.hasLoadedFileDependencies())
executable.loadFileDependencies();
// A bit of a hack. Executable compiles the code itself into a function, but we want
// the raw code to eval here.
var code = executable._code;
// Not clear why these should be global, varing them doesn't seem to take effect with evaluateString.
global.objj_executeFile = Executable.fileExecuterForURL(FILE.cwd());
global.objj_importFile = Executable.fileImporterForURL(FILE.cwd());
if (typeof system !== "undefined" && system.engine === "rhino")
return Packages.org.mozilla.javascript.Context.getCurrentContext().evaluateString(global, code, "objj_eval", 0, NULL);
return eval(code);
}
Executable.setCommonJSParameters("require", "exports", "module", "system", "print", "window");
// creates a narwhal factory function in the objj module scope
exports.make_narwhal_factory = function(path)
{
return function(require, exports, module, system, print)
{
Executable.setCommonJSParameters("require", "exports", "module", "system", "print", "window");
Executable.setCommonJSArguments(require, exports, module, system, print, window);
Executable.fileImporterForURL(FILE.dirname(path))(path, YES);
}
@@ -178,5 +161,26 @@ exports.make_narwhal_factory = function(path)
} // end "with"
var pkg = null;
function getPackage() {
if (!pkg)
pkg = JSON.parse(FILE.path(module.path).dirname().dirname().join("package.json").read({ charset : "UTF-8" }));
return pkg;
}
exports.version = function() { return getPackage()["version"]; }
exports.revision = function() { return getPackage()["cappuccino-revision"]; }
exports.timestamp = function() { return new Date(getPackage()["cappuccino-timestamp"]); }
exports.fullVersionString = function() {
return sprintf("objective-j %s (%04d-%02d-%02d %s)",
exports.version(),
exports.timestamp().getUTCFullYear(),
exports.timestamp().getUTCMonth()+1,
exports.timestamp().getUTCDate(),
exports.revision().slice(0,6)
);
}
if (require.main == module.id)
exports.run(system.args);
@@ -16,8 +16,7 @@ var Task = Jake.Task,
function isImage(/*String*/ aFilename)
{
return FILE.isFile(aFilename) &&
UTIL.has([".png", ".jpg", ".jpeg", ".gif", ".tif", ".tiff"], FILE.extension(aFilename).toLowerCase());
return UTIL.has([".png", ".jpg", ".jpeg", ".gif", ".tif", ".tiff"], FILE.extension(aFilename).toLowerCase());
}
function mimeType(/*String*/ aFilename)
@@ -370,14 +369,17 @@ BundleTask.prototype.infoPlist = function()
return anEnvironment.name();
}));
infoPlist.setValueForKey("CPBundleExecutable", this.productName() + ".sj");
infoPlist.setValueForKey("CPBundleEnvironmentsWithImageSprites", this.environments().filter(
var environmentsWithImageSprites = this.environments().filter(
function(anEnvironment)
{
return anEnvironment.spritesImages();
}).map(function(anEnvironment)
return anEnvironment.spritesImages() && task(this.buildProductDataURLPathForEnvironment(anEnvironment)).prerequisites().filter(isImage).length > 0;
}, this).map(function(anEnvironment)
{
return anEnvironment.name();
}));
});
infoPlist.setValueForKey("CPBundleEnvironmentsWithImageSprites", environmentsWithImageSprites);
var principalClass = this.principalClass();
@@ -581,7 +583,6 @@ BundleTask.prototype.defineResourceTasks = function()
}, this);
}
var RESOURCES_PATH = FILE.join(FILE.absolute(FILE.dirname(module.path)), "RESOURCES"),
MHTMLTestPath = FILE.join(RESOURCES_PATH, "MHTMLTest.txt");
@@ -595,27 +596,29 @@ BundleTask.prototype.defineSpritedImagesTask = function()
var folder = anEnvironment.name() + ".environment",
resourcesPath = FILE.join(this.buildIntermediatesProductPath(), folder, "Resources", "");
function isDataResource(/*String*/ aFilename)
{
return FILE.isFile(aFilename) && aFilename.indexOf(resourcesPath) === 0 && isImage(aFilename);
}
var productName = this.productName(),
dataURLPath = this.buildProductDataURLPathForEnvironment(anEnvironment);
filedir (dataURLPath, function(aTask)
{
var prerequisites = aTask.prerequisites().filter(isImage);
if (!prerequisites.length)
{
if (FILE.exists(dataURLPath))
FILE.remove(dataURLPath);
return;
}
TERM.stream.print("Creating data URLs file... \0green(" + dataURLPath +"\0)");
var dataURLStream = FILE.open(dataURLPath, "w+", { charset:"UTF-8" });
dataURLStream.write("@STATIC;1.0;");
aTask.prerequisites().forEach(function(aFilename)
prerequisites.forEach(function(aFilename)
{
if (!isDataResource(aFilename))
return;
var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename);
dataURLStream.write("u;" + resourcePath.length + ";" + resourcePath);
@@ -636,17 +639,24 @@ BundleTask.prototype.defineSpritedImagesTask = function()
filedir (MHTMLPath, function(aTask)
{
var prerequisites = aTask.prerequisites().filter(isImage);
if (!prerequisites.length)
{
if (FILE.exists(MHTMLPath))
FILE.remove(MHTMLPath);
return;
}
TERM.stream.print("Creating MHTML paths file... \0green(" + MHTMLPath +"\0)");
var MHTMLStream = FILE.open(MHTMLPath, "w+", { charset:"UTF-8" });
MHTMLStream.write("@STATIC;1.0;");
aTask.prerequisites().forEach(function(aFilename)
prerequisites.forEach(function(aFilename)
{
if (!isDataResource(aFilename))
return;
var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename),
MHTMLResourcePath = "mhtml:" + FILE.join(folder, "MHTMLData.txt!") + resourcePath;
@@ -663,17 +673,24 @@ BundleTask.prototype.defineSpritedImagesTask = function()
filedir (MHTMLDataPath, function(aTask)
{
var prerequisites = aTask.prerequisites().filter(isImage);
if (!prerequisites.length)
{
if (FILE.exists(MHTMLDataPath))
FILE.remove(MHTMLDataPath);
return;
}
TERM.stream.print("Creating MHTML images file... \0green(" + MHTMLDataPath +"\0)");
var MHTMLDataStream = FILE.open(MHTMLDataPath, "w+", { charset:"UTF-8" });
MHTMLDataStream.write("/*\r\nContent-Type: multipart/related; boundary=\"_ANY_STRING_WILL_DO_AS_A_SEPARATOR\"\r\n\r\n");
aTask.prerequisites().forEach(function(aFilename)
prerequisites.forEach(function(aFilename)
{
if (!isDataResource(aFilename))
return;
var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename);
MHTMLDataStream.write("--_ANY_STRING_WILL_DO_AS_A_SEPARATOR\r\n");
-1
View File
@@ -5,7 +5,6 @@
"description": "Objective-J and Cappuccino module",
"keywords": ["objective-j", "objj", "objective j", "cappuccino"],
"author": "280 North, Inc. (http://280north.com/)",
"version": "0.8.0",
"contributors": [
"Francisco Tolmasky (http://tolmasky.com/)",
"Ross Boucher (http://rossboucher.com/)",
+6 -1
View File
@@ -27,7 +27,7 @@ if (typeof window !== "undefined")
window.setNativeTimeout = window.setTimeout;
window.clearNativeTimeout = window.clearTimeout;
window.setNativeInterval = window.setInterval;
window.clearNativeInterval = window.clearNativeInterval;
window.clearNativeInterval = window.clearInterval;
}
// Objective-J Constants
@@ -73,3 +73,8 @@ GLOBAL(PI_2) = Math.PI / 2.0;
GLOBAL(SQRT1_2) = Math.SQRT1_2;
GLOBAL(SQRT2) = Math.SQRT2;
GLOBAL(OBJJ_MEMORY_TABLE) = [];
GLOBAL($) = function(pointer) { return OBJJ_MEMORY_TABLE[pointer]; }
GLOBAL($$) = function(object) { return object._UID; }
+5
View File
@@ -20,6 +20,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
CPLogRegister(CPLogDefault);
// formatting helpers
function objj_debug_object_format(aReceiver)
@@ -215,3 +217,6 @@ GLOBAL(objj_debug_typecheck) = function(expectedType, object)
throw ("expected=" + expectedType + ", actual=" + actualType);
}
if (typeof window.OBJJ_ZOMBIE_DETECTION === "undefined")
OBJJ_ZOMBIE_DETECTION = false;
+55
View File
@@ -0,0 +1,55 @@
GLOBAL(objj_eval) = function(/*String*/ aString)
{
#if COMMONJS
var url = FILE.join(FILE.cwd(), "/");
Executable.setCommonJSParameters("require", "exports", "module", "system", "print", "window");
Executable.setCommonJSArguments(require, exports, module, system, print, window);
#else
var url = exports.pageURL;
#endif
// Temporarily switch the loader to sychronous mode since objj_eval must be synchronous
// therefore you shouldn't use @imports in objj_eval the browser
var asyncLoaderSaved = exports.asyncLoader;
exports.asyncLoader = NO;
var executable = exports.preprocess(aString, url, 0);
if (!executable.hasLoadedFileDependencies())
executable.loadFileDependencies();
// here we setup a scope object containing the free variables that would normally be arguments to the module function
global._objj_eval_scope = {};
global._objj_eval_scope.objj_executeFile = Executable.fileExecuterForURL(url);
global._objj_eval_scope.objj_importFile = Executable.fileImporterForURL(url);
#if COMMONJS
global._objj_eval_scope.require = require;
global._objj_eval_scope.exports = exports;
global._objj_eval_scope.module = module;
global._objj_eval_scope.system = system;
global._objj_eval_scope.print = print;
global._objj_eval_scope.window = window;
#endif
// A bit of a hack. Executable compiles the code itself into a function, but we want
// the raw code to eval here so we can get the result.
// No known way to get the result of a statement except via eval.
var code = "with(_objj_eval_scope){" + executable._code + "\n//*/\n}";
var result;
#if COMMONJS
if (typeof system !== "undefined" && system.engine === "rhino")
result = Packages.org.mozilla.javascript.Context.getCurrentContext().evaluateString(global, code, "objj_eval", 0, NULL);
else
#endif
result = eval(code);
// restore async loader setting
exports.asyncLoader = asyncLoaderSaved;
return result;
}
// deprecated, use global
exports.objj_eval = objj_eval;

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