repo
string
commit
string
message
string
diff
string
markpasc/mt-plugin-action-streams
7946221581992094491bd0c927848b6d56381d5f
Fixed BugID:89499 * Added hint, label, examples * Modified template which enables hint showing
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml index eac0de0..4aaf86f 100644 --- a/plugins/ActionStreams/services.yaml +++ b/plugins/ActionStreams/services.yaml @@ -1,317 +1,340 @@ oneup: name: 1up.com url: http://{{ident}}.1up.com/ fortythreethings: name: 43Things url: http://www.43things.com/person/{{ident}}/ aim: name: AIM url: aim:goim?screenname={{ident}} ident_label: Screen name service_type: contact backtype: name: backtype url: http://www.backtype.com/{{ident}} service_type: comments bebo: name: Bebo url: http://www.bebo.com/Profile.jsp?MemberId={{ident}} service_type: network catster: name: Catster url: http://www.catster.com/cats/{{ident}} colourlovers: name: COLOURlovers url: http://www.colourlovers.com/lover/{{ident}} corkd: name: 'Cork''d' url: http://www.corkd.com/people/{{ident}} delicious: name: Delicious url: http://delicious.com/{{ident}}/ service_type: links destructoid: name: Destructoid url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}} digg: name: Digg url: http://digg.com/users/{{ident}}/ service_type: links dodgeball: name: Dodgeball url: http://www.dodgeball.com/user?uid={{ident}} dogster: name: Dogster url: http://www.dogster.com/dogs/{{ident}} dopplr: name: Dopplr url: http://www.dopplr.com/traveller/{{ident}}/ facebook: name: Facebook url: http://www.facebook.com/profile.php?id={{ident}} ident_label: User ID ident_example: 12345 service_type: network + ident_hint: You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320. ffffound: name: FFFFOUND! url: http://ffffound.com/home/{{ident}}/found/ service_type: photos flickr: name: Flickr url: http://flickr.com/photos/{{ident}}/ ident_example: 36381329@N00 service_type: photos + ident_hint: Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream. friendfeed: name: FriendFeed url: http://friendfeed.com/{{ident}} ident_example: JoeUsername gametap: name: Gametap url: http://www.gametap.com/profile/show/profile.do?sn={{ident}} gblogs: name: Google Blogs url: http://blogsearch.google.com/blogsearch?q=%s # icon: http://www.google.com/mobile/images/news-24x24.gif - ident-label: Search term + ident_label: Search term gnews: name: Google News url: http://news.google.com/news?q=%s # icon: http://www.google.com/mobile/images/news-24x24.gif ident_label: Search for goodreads: name: Goodreads url: http://www.goodreads.com/user/show/{{ident}} ident_label: User ID ident_example: 12345 + ident_hint: You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456. googlereader: name: Google Reader url: http://www.google.com/reader/shared/{{ident}} ident_label: Sharing ID ident_example: http://www.google.com/reader/shared/16793324975410272738 service_type: links hi5: name: Hi5 url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}} service_type: network iconbuffet: name: IconBuffet url: http://www.iconbuffet.com/people/{{ident}} icq: name: ICQ url: http://www.icq.com/people/about_me.php?uin={{ident}} ident_label: UIN ident_example: 12345 service_type: contact identica: name: Identi.ca url: http://identi.ca/{{ident}} service_type: status iminta: name: Iminta url: http://iminta.com/people/{{ident}} istockphoto: name: iStockPhoto url: http://www.istockphoto.com/user_view.php?id={{ident}} ident_label: User ID ident_example: 123456 + ident_hint: You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567. iusethis: name: IUseThis url: http://osx.iusethis.com/user/{{ident}} iwatchthis: name: iwatchthis url: http://iwatchthis.com/{{ident}} jabber: name: Jabber url: jabber://{{ident}} ident_label: Jabber ID ident_example: [email protected] service_type: contact jaiku: name: Jaiku url: http://{{ident}}.jaiku.com/ ident_suffix: .jaiku.com service_type: status kongregate: name: Kongregate url: http://www.kongregate.com/accounts/{{ident}} lastfm: name: Last.fm url: http://www.last.fm/user/{{ident}}/ ident_example: JoeUsername linkedin: name: LinkedIn url: http://www.linkedin.com/in/{{ident}} ident_example: MelodyNelson + ident_prefix: http://www.linkedin.com/in/ + ident_label: Profile URL service_type: network livejournal: name: LiveJournal url: http://{{ident}}.livejournal.com/ ident_suffix: .livejournal.com service_type: blog magnolia: name: Ma.gnolia url: http://ma.gnolia.com/people/{{ident}} service_type: links mog: name: MOG url: http://mog.com/{{ident}} msn: name: 'MSN Messenger' url: msnim:chat?contact={{ident}} service_type: contact multiply: name: Multiply url: http://{{ident}}.multiply.com/ myspace: name: MySpace url: http://www.myspace.com/{{ident}} + ident_label: User ID + ident_prefix: http://www.myspace.com/ service_type: network netflix: name: Netflix url: http://rss.netflix.com/QueueRSS?id={{ident}} ident_label: Netflix RSS ID ident_example: P0000006746939516625352861892808956 + ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link. netvibes: name: Netvibes url: http://www.netvibes.com/{{ident}} service_type: links newsvine: name: Newsvine url: http://{{ident}}.newsvine.com/ ning: name: Ning url: http://{{ident}}.ning.com/ service_type: network + ident_suffix: .ning.com/ + ident_prefix: http:// + ident_label: Social Network URL ohloh: name: Ohloh url: http://ohloh.net/accounts/{{ident}} orkut: name: Orkut url: http://www.orkut.com/Profile.aspx?uid={{ident}} + ident_label: User ID + ident_example: 1234567890123456789 service_type: network + ident_hint: You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789 pandora: name: Pandora url: http://pandora.com/people/{{ident}} ident_example: JoeUsername picasaweb: name: Picasa Web Albums url: http://picasaweb.google.com/{{ident}} service_type: photos p0pulist: name: p0pulist url: http://p0pulist.com/list/hot_list/{{ident}} ident_label: User ID ident_example: 12345 + ident_hint: You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000 pownce: name: Pownce url: http://pownce.com/{{ident}}/ service_type: status reddit: name: Reddit url: http://reddit.com/user/{{ident}}/ service_type: links skype: name: Skype url: callto://{{ident}} slideshare: name: SlideShare url: http://www.slideshare.net/{{ident}} smugmug: name: Smugmug url: http://{{ident}}.smugmug.com/ service_type: photos sonicliving: name: SonicLiving url: http://www.sonicliving.com/user/{{ident}}/ + ident_label: User ID + ident_example: 12345 + ident_hint: You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds steam: name: Steam url: http://steamcommunity.com/id/{{ident}} stumbleupon: name: StumbleUpon url: http://{{ident}}.stumbleupon.com/ tabblo: name: Tabblo url: http://www.tabblo.com/studio/person/{{ident}}/ technorati: name: Technorati url: http://technorati.com/people/technorati/{{ident}} tribe: name: Tribe url: http://people.tribe.net/{{ident}} service_type: network + ident_label: User ID + ident_hint: You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a. tumblr: name: Tumblr url: http://{{ident}}.tumblr.com icon: images/services/tumblr.gif ident_label: URL ident_suffix: .tumblr.com service_type: blog twitter: name: Twitter url: http://twitter.com/{{ident}} service_type: status typepad: name: TypePad ident_prefix: http://profile.typepad.com/ ident_label: Profile URL url: http://profile.typepad.com/{{ident}} uncrate: name: Uncrate url: http://uncrate.com/stuff/{{ident}} upcoming: name: Upcoming url: http://upcoming.yahoo.com/user/{{ident}} ident_label: User ID ident_example: 12345 viddler: name: Viddler url: http://www.viddler.com/explore/{{ident}} service_type: video vimeo: name: Vimeo url: http://www.vimeo.com/{{ident}} service_type: video virb: name: Virb url: http://www.virb.com/{{ident}} service_type: network + ident_label: User ID + ident_hint: You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home. vox: name: Vox url: http://{{ident}}.vox.com/ ident_label: Vox name ident_suffix: .vox.com service_type: blog website: name: Website url: '{{ident}}' ident_label: URL ident_example: http://www.example.com/ ident_exact: 1 can_many: 1 service_type: blog wists: name: Wists url: http://www.wists.com/{{ident}} xboxlive: name: 'Xbox Live' url: http://live.xbox.com/member/{{ident}} ident_label: Gamertag yahoo: name: 'Yahoo! Messenger' url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}} service_type: contact yelp: name: Yelp url: http://www.yelp.com/user_details?userid={{ident}} ident_label: User ID ident_example: 4BXqlLKW8oP0RBCW1FvaIg youtube: name: YouTube url: http://www.youtube.com/user/{{ident}} service_type: video zooomr: name: Zooomr url: http://www.zooomr.com/photos/{{ident}} ident_example: 1234567@Z01 service_type: photos diff --git a/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl b/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl index 2cee720..e3022b7 100644 --- a/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl +++ b/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl @@ -1,210 +1,213 @@ <mt:setvarblock name="page_title"><__trans phrase="Add Profile"></mt:setvarblock> <mt:setvarblock name="html_head" append="1"> <link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" /> <mt:loop name="service_styles"> <mt:if name="__first__"> <style type="text/css"> <!-- </mt:if> .service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); } <mt:if name="__last__"> // --> </style> </mt:if> </mt:loop> <script type="text/javascript"> <!-- function validate(f) { if (!f.profile_id.value) { alert('<__trans phrase="Your user name or ID is required." escape="singlequotes">'); return false; } return true; } // --> </script> </mt:setvarblock> <mt:include name="dialog/header.tmpl"> <script type="text/javascript" src="<mt:var name="static_uri">js/tc/client.js"></script> <script type="text/javascript" src="<mt:var name="static_uri">js/dialog.js"></script> <div class="modal_width" id="add-profile"> <p>Add a profile on a social networking or instant messaging service.</p> <form id="add-network" method="post" action="<mt:var name="script_url">" onsubmit="return validate(this)" target="_top"> <input type="hidden" name="__mode" value="add_other_profile" /> <input type="hidden" name="author_id" value="<mt:var name="edit_author_id">" /> <input type="hidden" name="magic_token" value="<mt:var name="magic_token">" /> <mtapp:setting id="profile_type" label="<__trans phrase="Service">" hint="<__trans phrase="Select a service where you already have an account.">" show_hint="1" content_class="field-content-text"> <select name="profile_type" id="profile_type"> <mt:loop name="networks"> <mt:if name="user_has_account"> <mt:if name="can_many"> <option value="<mt:var name="type" escape="html">"><mt:var name="label" escape="html"></option> </mt:if> <mt:else> <option value="<mt:var name="type" escape="html">"><mt:var name="label" escape="html"></option> </mt:if> </mt:loop> </select> </mtapp:setting> <script type="text/javascript"> var last_network; var networks = { <mt:loop name="networks"> '<mt:var name="type" escape="js">': { <mt:if name="ident_example"> example: '<mt:var name="ident_example" escape="js">', </mt:if> <mt:if name="ident_prefix"> prefix: '<mt:var name="ident_prefix" escape="js">', </mt:if> <mt:if name="ident_suffix"> suffix: '<mt:var name="ident_suffix" escape="js">', </mt:if> + <mt:if name="ident_hint"> + hint: '<mt:var name="ident_hint" escape="js">', + </mt:if> label: '<mt:var name="ident_label" escape="js">' }<mt:unless var="__last__">,</mt:unless> </mt:loop> }; function update_ident_field () { var v = getByID('profile_type'); var data = new Object(); data.label = "Username"; data.example = "melody"; data.prefix = ""; data.suffix = ""; var fields = ['label', 'example', 'prefix', 'suffix']; for(var i = 0; i < 4; i++) { var l = fields[i]; var datum = data[l]; if (networks[v.value] && networks[v.value][l]) { datum = networks[v.value][l]; } var f = getByID('profile_id-' + l); f.innerHTML = datum; } + if (networks[v.value] && networks[v.value]['hint']) { + var f = getByID('profile_id-hint-inner'); + f.innerHTML = networks[v.value]['hint']; + show('profile_id-hint',document); + } else { + hide('profile_id-hint',document); + } if (last_network) { - hide('help-' + last_network, document); hide('streams-' + last_network, document); var streams = getByID('streams-' + last_network); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; stream_boxes[i].checked = false; } } - show('help-' + v.value, document); show('streams-' + v.value, document); var streams = getByID('streams-' + v.value); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; stream_boxes[i].checked = true; } var icon = getByID('profile-id-service-icon'); if (last_network) { DOM.removeClassName(icon, 'service-' + last_network); } DOM.addClassName(icon, 'service-' + v.value); last_network = v.value; } function add_in_update (e) { var v = getByID('profile_type'); DOM.addEventListener(v, 'change', update_ident_field); update_ident_field(); } TC.attachLoadEvent(add_in_update); </script> <mtapp:setting id="profile_id" label="<__trans phrase="Username">" hint="<__trans phrase="Enter your account on the selected service."><br /><__trans phrase="For example:"> <strong id='profile_id-example'>melody</strong>" show_hint="1" content_class="field-content-text"> <span id="profile-id-service-icon" class="service-icon"> <span id="profile_id-prefix"></span> <input type="text" name="profile_id" size="30" value="" /> <span id="profile_id-suffix"></span> </span> </mtapp:setting> - <div id="help-facebook" class="hidden"> - <div class="hint">You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.</div> + <div id="profile_id-hint" class="hidden"> + <div id="profile_id-hint-inner" class="hint"></div> </div> <div id="help-netflix" class="hidden"> - <mtapp:statusmsg class="info">To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.</mtapp:statusmsg> - </div> - - <div id="help-flickr" class="hidden"> - <div class="hint">Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.</div> </div> <h3>Action Streams</h3> <p>Select the action streams to collect from the selected service.</p> <mt:loop name="networks"> <div id="streams-<mt:var name="type" escape="html">" class="hidden"> <mt:if name="streams"> <mt:loop name="streams"> <mt:setvarblock name="stream_id">stream_<mt:var name="type" escape="html">_<mt:var name="stream" escape="html"></mt:setvarblock> <mtapp:setting id="<mt:var name="stream_id">" label="<mt:var name="name" escape="html">"> <label><input type="checkbox" id="<mt:var name="stream_id">" name="<mt:var name="stream_id">" value="1" /> <mt:var name="description" escape="html"></label> </mtapp:setting> </mt:loop> <mt:else> <mtapp:statusmsg class="info zero-state">No streams are available for this service.</mtapp:statusmsg> </mt:if> </div> </mt:loop> <mt:setvarblock name="action_buttons"> <button type="submit" accesskey="s" title="<__trans phrase="Add Service (s)">" class="primary-button" ><__trans phrase="Add Service"></button> <button onclick="closeDialog(); return false" type="submit" accesskey="x" title="<__trans phrase="Cancel (x)">" class="cancel" ><__trans phrase="Cancel"></button> </mt:setvarblock> <mt:include name="include/actions_bar.tmpl" bar_position="normal" hide_pager="1" settings_bar="1"> </form> </div> <mt:include name="dialog/footer.tmpl"> diff --git a/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl b/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl index 0403a73..ac285f5 100644 --- a/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl +++ b/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl @@ -1,207 +1,209 @@ <mt:setvarblock name="page_title"><__trans phrase="Edit Profile"></mt:setvarblock> <mt:setvarblock name="html_head" append="1"> <link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" /> <mt:loop name="service_styles"> <mt:if name="__first__"> <style type="text/css"> <!-- </mt:if> .service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); } <mt:if name="__last__"> // --> </style> </mt:if> </mt:loop> <script type="text/javascript"> <!-- function validate(f) { if (!f.profile_id.value) { alert('<__trans phrase="Your user name or ID is required." escape="singlequotes">'); return false; } return true; } // --> </script> </mt:setvarblock> <mt:include name="dialog/header.tmpl"> <script type="text/javascript" src="<mt:var name="static_uri">js/tc/client.js"></script> <script type="text/javascript" src="<mt:var name="static_uri">js/dialog.js"></script> <div class="modal_width" id="edit-profile"> <p>Edit a profile on a social networking or instant messaging service.</p> <form id="edit-network" method="post" action="<mt:var name="script_url">" onsubmit="return validate(this)" target="_top"> <input type="hidden" name="__mode" value="edit_other_profile" /> <input type="hidden" name="author_id" value="<mt:var name="edit_author_id">" /> <input type="hidden" name="original_ident" value="<mt:var name="edit_ident" escape="html">" /> <input type="hidden" name="magic_token" value="<mt:var name="magic_token">" /> <mtapp:setting id="profile_type" label="<__trans phrase="Service">" content_class="field-content-text"> <strong><mt:var name="edit_type_name" escape="html"></strong> <input type="hidden" name="profile_type" id="profile_type" value="<mt:var name="edit_type" escape="html">" /> </mtapp:setting> <script type="text/javascript"> var last_network; var networks = { <mt:loop name="networks"> '<mt:var name="type" escape="js">': { <mt:if name="ident_example"> example: '<mt:var name="ident_example" escape="js">', </mt:if> <mt:if name="ident_prefix"> prefix: '<mt:var name="ident_prefix" escape="js">', </mt:if> <mt:if name="ident_suffix"> suffix: '<mt:var name="ident_suffix" escape="js">', </mt:if> + <mt:if name="ident_hint"> + hint: '<mt:var name="ident_hint" escape="js">', + </mt:if> label: '<mt:var name="ident_label" escape="js">' }<mt:unless var="__last__">,</mt:unless> </mt:loop> }; var edit_streams = { <mt:loop name="edit_streams"> 'stream_<mt:var name="__key__" escape="js">': '<mt:var name="__value__" escape="js">'<mt:unless name="__last__">,</mt:unless> </mt:loop> }; function update_ident_field () { var v = getByID('profile_type'); var data = new Object(); data.label = "Username"; data.example = "melody"; data.prefix = ""; data.suffix = ""; var fields = ['label', 'example', 'prefix', 'suffix']; for(var i = 0; i < 4; i++) { var l = fields[i]; var datum = data[l]; if (networks[v.value] && networks[v.value][l]) { datum = networks[v.value][l]; } var f = getByID('profile_id-' + l); f.innerHTML = datum; } + if (networks[v.value] && networks[v.value]['hint']) { + var f = getByID('profile_id-hint-inner'); + f.innerHTML = networks[v.value]['hint']; + show('profile_id-hint',document); + } else { + hide('profile_id-hint',document); + } if (last_network) { hide('help-' + last_network, document); hide('streams-' + last_network, document); var streams = getByID('streams-' + last_network); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; stream_boxes[i].checked = false; } } show('help-' + v.value, document); show('streams-' + v.value, document); var streams = getByID('streams-' + v.value); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; if (edit_streams[ stream_boxes[i].name ]) stream_boxes[i].checked = true; } var icon = getByID('profile-id-service-icon'); if (last_network) { DOM.removeClassName(icon, 'service-' + last_network); } DOM.addClassName(icon, 'service-' + v.value); last_network = v.value; } function add_in_update (e) { var v = getByID('profile_type'); DOM.addEventListener(v, 'change', update_ident_field); update_ident_field(); } TC.attachLoadEvent(add_in_update); </script> <mtapp:setting id="profile_id" label="<__trans phrase="Username">" hint="<__trans phrase="Enter your account on the selected service."><br /><__trans phrase="For example:"> <strong id='profile_id-example'>melody</strong>" show_hint="1" content_class="field-content-text"> <span id="profile-id-service-icon" class="service-icon"> <span id="profile_id-prefix"></span> <input type="text" name="profile_id" size="30" value="<mt:var name="edit_ident" escape="html">" /> <span id="profile_id-suffix"></span> </span> </mtapp:setting> - <div id="help-facebook" class="hidden"> - <div class="hint">You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.</div> - </div> - - <div id="help-netflix" class="hidden"> - <mtapp:statusmsg class="info">To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.</mtapp:statusmsg> - </div> - - <div id="help-flickr" class="hidden"> - <div class="hint">Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.</div> + <div id="profile_id-hint" class="hidden"> + <div id="profile_id-hint-inner" class="hint"></div> </div> <h3>Action Streams</h3> <p>Select the action streams to collect from the selected service.</p> <mt:loop name="networks"> <div id="streams-<mt:var name="type" escape="html">" class="hidden"> <mt:if name="streams"> <mt:loop name="streams"> <mt:setvarblock name="stream_id">stream_<mt:var name="type" escape="html">_<mt:var name="stream" escape="html"></mt:setvarblock> <mtapp:setting id="<mt:var name="stream_id">" label="<mt:var name="name" escape="html">"> <label><input type="checkbox" id="<mt:var name="stream_id">" name="<mt:var name="stream_id">" value="1" /> <mt:var name="description" escape="html"></label> </mtapp:setting> </mt:loop> <mt:else> <mtapp:statusmsg class="info zero-state">No streams are available for this service.</mtapp:statusmsg> </mt:if> </div> </mt:loop> <mt:setvarblock name="action_buttons"> <button type="submit" accesskey="s" title="<__trans phrase="Save Changes (s)">" class="primary-button" ><__trans phrase="Save Changes"></button> <button onclick="closeDialog(); return false" type="submit" accesskey="x" title="<__trans phrase="Cancel (x)">" class="cancel" ><__trans phrase="Cancel"></button> </mt:setvarblock> <mt:include name="include/actions_bar.tmpl" bar_position="normal" hide_pager="1" settings_bar="1"> </form> </div> <mt:include name="dialog/footer.tmpl">
markpasc/mt-plugin-action-streams
ac1745ff3e1ab2914539e65deb7404b422f6720f
Added destructoid service image. BugzID:89526
diff --git a/mt-static/plugins/ActionStreams/images/services/destructoid.png b/mt-static/plugins/ActionStreams/images/services/destructoid.png new file mode 100644 index 0000000..4179ff4 Binary files /dev/null and b/mt-static/plugins/ActionStreams/images/services/destructoid.png differ
markpasc/mt-plugin-action-streams
d1f67040488a4d7146ea26731dad3ef53b6699f3
Revert changes r1365 BugId:89294
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm index 76c8f1e..418dace 100644 --- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm +++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm @@ -1,465 +1,464 @@ package ActionStreams::Tags; use strict; use MT::Util qw( offset_time_list epoch2ts ts2epoch ); use ActionStreams::Plugin; sub stream_action { my ($ctx, $args, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamAction in a non-action-stream context!"); return $event->as_html( defined $args->{name} ? (name => $args->{name}) : () ); } sub stream_action_id { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); return $event->id || ''; } sub stream_action_var { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVar in a non-action-stream context!"); my $var = $arg->{var} || $arg->{name} or return $ctx->error("Used StreamActionVar without a 'name' attribute!"); return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event) if !$event->can($var) && !$event->has_column($var); return $event->$var(); } sub stream_action_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionDate in a non-action-stream context!"); my $c_on = $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) ) if $c_on; return $ctx->_hdlr_date($arg); } sub stream_action_modified_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!"); my $m_on = $event->modified_on || $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) ) if $m_on; return $ctx->_hdlr_date($arg); } sub stream_action_title { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionTitle in a non-action-stream context!"); return $event->title || ''; } sub stream_action_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); return $event->url || ''; } sub stream_action_thumbnail_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!"); return $event->thumbnail || ''; } sub stream_action_via { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVia in a non-action-stream context!"); return $event->via || q{}; } sub other_profile_var { my( $ctx, $args ) = @_; my $profile = $ctx->stash( 'other_profile' ) or return $ctx->error( 'No profile defined in ProfileVar' ); my $var = $args->{name} || 'uri'; return defined $profile->{ $var } ? $profile->{ $var } : ''; } sub _author_ids_for_args { my ($ctx, $args, $cond) = @_; my @author_ids; if (my $ids = $args->{author_ids} || $args->{author_id}) { @author_ids = split /\s*,\s*/, $ids; } elsif (my $disp_names = $args->{display_names} || $args->{display_name}) { my @names = split /\s*,\s*/, $disp_names; my @authors = MT->model('author')->load({ nickname => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $names = $args->{author} || $args->{authors}) { # If arg is the special string 'all', then include all authors by returning undef instead of an empty array. return if $names =~ m{ \A\s* all \s*\z }xmsi; my @names = split /\s*,\s*/, $names; my @authors = MT->model('author')->load({ name => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $author = $ctx->stash('author')) { @author_ids = ( $author->id ); } elsif (my $blog = $ctx->stash('blog')) { my @authors = MT->model('author')->load({ status => 1, # enabled }, { join => MT->model('permission')->join_on('author_id', { blog_id => $blog->id }, { unique => 1 }), }); @author_ids = map { $_->[0]->id } grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post } map { [ $_, $_->permissions($blog->id) ] } @authors; } return \@author_ids; } sub action_streams { my ($ctx, $args, $cond) = @_; my %terms = ( class => '*', visible => 1, ); my $author_id = _author_ids_for_args(@_); $terms{author_id} = $author_id if defined $author_id; my %args = ( sort => ($args->{sort_by} || 'created_on'), direction => ($args->{direction} || 'descend'), ); my $app = MT->app; undef $app unless $app->isa('MT::App'); if (my $limit = $args->{limit} || $args->{lastn}) { $args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit; } elsif (my $days = $args->{days}) { my @ago = offset_time_list(time - 3600 * 24 * $days, $ctx->stash('blog')); my $ago = sprintf "%04d%02d%02d%02d%02d%02d", $ago[5]+1900, $ago[4]+1, @ago[3,2,1,0]; $terms{created_on} = [ $ago ]; $args{range_incl}{created_on} = 1; } else { $args{limit} = 20; } if (my $offset = $args->{offset}) { if ($offset eq 'auto') { $args{offset} = $app->param('offset') if $app && $app->param('offset') > 0; } elsif ($offset =~ m/^\d+$/) { $args{offset} = $offset; } } my ($service, $stream) = @$args{qw( service stream )}; if ($service && $stream) { $terms{class} = join q{_}, $service, $stream; } elsif ($service) { $terms{class} = $service . '_%'; $args{like} = { class => 1 }; } elsif ($stream) { $terms{class} = '%_' . $stream; $args{like} = { class => 1 }; } # Make sure all classes are loaded. require ActionStreams::Event; for my $service (keys %{ MT->instance->registry('action_streams') || {} }) { ActionStreams::Event->classes_for_type($service); } - $app->run_callbacks('actionstreams_pre_search', \%terms, \%args ); my @events = ActionStreams::Event->search(\%terms, \%args); return $ctx->_hdlr_pass_tokens_else($args, $cond) if !@events; if ($args{sort} eq 'created_on') { @events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events; @events = reverse @events if $args{direction} ne 'descend'; } local $ctx->{__stash}{remaining_stream_actions} = \@events; my $res = ''; my ($count, $total) = (0, scalar @events); my $day_date = ''; EVENT: while (my $event = shift @events) { my $new_day_date = _event_day($ctx, $event); local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0; local $cond->{DateFooter} = !@events ? 1 : $new_day_date ne _event_day($ctx, $events[0]) ? 1 : 0 ; $day_date = $new_day_date; $count++; defined (my $out = _build_about_event( $ctx, $args, $cond, event => $event, count => $count, total => $total, )) or return; $res .= $out; } return $res; } sub _build_about_event { my ($ctx, $arg, $cond, %param) = @_; my ($event, $count, $total) = @param{qw( event count total )}; local $ctx->{__stash}{stream_action} = $event; my $author = $event->author; local $ctx->{__stash}{author} = $event->author; my $type = $event->class_type; my ($service, $stream_id) = split /_/, $type, 2; my $profile = $author->other_profiles($service); next EVENT if !$profile; local $ctx->{__stash}{other_profile} = $profile; my $vars = $ctx->{__stash}{vars} ||= {}; local $vars->{action_type} = $type; local $vars->{service_type} = $service; local $vars->{stream_type} = $stream_id; local $vars->{__first__} = $count == 1; local $vars->{__last__} = $count == $total; local $vars->{__odd__} = ($count % 2) == 1; local $vars->{__even__} = ($count % 2) == 0; local $vars->{__counter__} = $count; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); return $out; } sub stream_action_rollup { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionRollup in a non-action-stream context!"); my $nexts = $ctx->stash('remaining_stream_actions'); return $ctx->else($arg, $cond) if !$nexts || !@$nexts; my $by_spec = $arg->{by} || 'date,action'; my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec; my $event_date = _event_day($ctx, $event); my $event_class = $event->class; my ($event_service, $event_stream) = split /_/, $event_class, 2; my @rollup_events = ($event); EVENT: while (@$nexts) { my $next = $nexts->[0]; last EVENT if $by{date} && $event_date ne _event_day($ctx, $next); last EVENT if $by{action} && $event_class ne $next->class; last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms; last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms; # Eligible to roll up! Remove it from the remaining actions. push @rollup_events, shift @$nexts; } return $ctx->else($arg, $cond) if 1 >= scalar @rollup_events; my $res; my $count = 0; for my $rup_event (@rollup_events) { $count++; defined (my $out = _build_about_event( $ctx, $arg, $cond, event => $rup_event, count => $count, total => scalar @rollup_events, )) or return; $res .= $arg->{glue} if $arg->{glue} && $count > 1; $res .= $out; } return $res; } sub _event_day { my ($ctx, $event) = @_; return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8); } sub stream_action_tags { my ($ctx, $args, $cond) = @_; require MT::Entry; my $event = $ctx->stash('stream_action'); return '' unless $event; my $glue = $args->{glue} || ''; local $ctx->{__stash}{tag_max_count} = undef; local $ctx->{__stash}{tag_min_count} = undef; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = ''; my $tags = $event->get_tag_objects; for my $tag (@$tags) { next if $tag->is_private && !$args->{include_private}; local $ctx->{__stash}{Tag} = $tag; local $ctx->{__stash}{tag_count} = undef; local $ctx->{__stash}{tag_event_count} = undef; # ? defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error( $builder->errstr ); $res .= $glue if $res ne ''; $res .= $out; } $res; } sub other_profiles { my( $ctx, $args, $cond ) = @_; my $author_ids = _author_ids_for_args(@_); my $author_id = shift @$author_ids or return $ctx->error('No author specified for OtherProfiles'); my $user = MT->model('author')->load($author_id) or return $ctx->error(MT->trans('No user [_1]', $author_id)); my @profiles = sort { lc $a->{type} cmp lc $b->{type} } @{ $user->other_profiles() }; my $services = MT->app->registry('profile_services'); if (my $filter_type = $args->{type}) { my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0; @profiles = grep { my $profile = $_; my $profile_type = $profile->{type}; my $service_type = ($services->{$profile_type} || {})->{service_type} || q{}; $filter_except ? $service_type ne $filter_type : $service_type eq $filter_type; } @profiles; } my $populate_icon = sub { my ($item, $row) = @_; my $type = $item->{type}; $row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type}); }; return list( context => $ctx, arguments => $args, conditions => $cond, items => \@profiles, stash_key => 'other_profile', code => $populate_icon, ); } sub list { my %param = @_; my ($ctx, $args, $cond) = @param{qw( context arguments conditions )}; my ($items, $stash_key, $code) = @param{qw( items stash_key code )}; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = q{}; my $glue = $args->{glue}; $glue = '' unless defined $glue; my $vars = ($ctx->{__stash}{vars} ||= {}); my ($count, $total) = (0, scalar @$items); for my $item (@$items) { local $ctx->{__stash}->{$stash_key} = $item; my $row = {}; $code->($item, $row) if $code; my $lvars = delete $row->{vars} if exists $row->{vars}; local @$vars{keys %$lvars} = values %$lvars if $lvars; local @{ $ctx->{__stash} }{keys %$row} = values %$row; $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; defined (my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); $res .= $glue if ($res ne '') && ($out ne '') && ($glue ne ''); $res .= $out; } return $res; } sub profile_services { my( $ctx, $args, $cond ) = @_; my $app = MT->app; my $networks = $app->registry('profile_services'); my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} } keys %$networks; my $out = ""; my $builder = $ctx->stash( 'builder' ); my $tokens = $ctx->stash( 'tokens' ); my $vars = ($ctx->{__stash}{vars} ||= {}); if ($args->{extra}) { # Skip output completely if it's a "core" service but we want # extras only. @network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys; } my ($count, $total) = (0, scalar @network_keys); for my $type (@network_keys) { $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; my $ndata = $networks->{$type}; local @$vars{keys %$ndata} = values %$ndata; local $vars->{label} = $ndata->{name}; local $vars->{type} = $type; local $vars->{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $networks->{$type}); local $ctx->{__stash}{profile_service} = $ndata; $out .= $builder->build( $ctx, $tokens, $cond ); } return $out; } 1;
markpasc/mt-plugin-action-streams
499e0917e069ab0d9d77ddb1c28809d2f44c2d22
Implemented a workaround of the issue that Oracle does not like the name of the meta table created by the Action Streams plugin. BugId:82819
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml index 8733dc9..dd1404e 100644 --- a/plugins/ActionStreams/config.yaml +++ b/plugins/ActionStreams/config.yaml @@ -1,183 +1,184 @@ name: Action Streams id: ActionStreams key: ActionStreams author_link: http://www.sixapart.com/ author_name: Six Apart Ltd. description: Manages authors' accounts and actions on sites elsewhere around the web schema_version: 16 version: 2.0 plugin_link: http://www.sixapart.com/ settings: rebuild_for_action_stream_events: Default: 0 Scope: blog blog_config_template: blog_config_template.tmpl init_app: $ActionStreams::ActionStreams::Init::init_app applications: cms: methods: list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events community: methods: profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile callbacks: post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events callbacks: MT::App::CMS::template_source.users_content_nav: $ActionStreams::ActionStreams::Plugin::users_content_nav MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb object_types: profileevent: ActionStreams::Event + as: ActionStreams::Event as_ua_cache: ActionStreams::UserAgent::Cache list_actions: profileevent: hide_all: label: Hide All order: 100 js: finishPluginActionAll code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events continue_prompt: 'Are you sure you want to hide EVERY event in EVERY action stream?' show_all: label: Show All order: 200 js: finishPluginActionAll code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events continue_prompt: 'Are you sure you want to show EVERY event in EVERY action stream?' delete: label: Delete order: 300 code: $core::MT::App::CMS::delete continue_prompt: 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' tags: function: StreamAction: $ActionStreams::ActionStreams::Tags::stream_action StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var block: ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup tasks: UpdateEvents: frequency: 1800 label: Poll for new events code: $ActionStreams::ActionStreams::Plugin::update_events task_workers: UpdateEvents: label: Update Events class: ActionStreams::Worker widgets: asotd: label: Recent Actions template: widget_recent.mtml permission: post singular: 1 set: sidebar handler: $ActionStreams::ActionStreams::Plugin::widget_recent condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only template_sets: streams: label: 'Action Stream' base_path: 'blog_tmpl' order: 100 templates: index: main_index: label: Main Index (Recent Actions) outfile: index.html rebuild_me: 1 archive: label: Action Archive outfile: archive.html rebuild_me: 1 styles: label: Stylesheet outfile: styles.css rebuild_me: 1 atom: label: Atom outfile: atom.xml rebuild_me: 1 module: header: label: Header footer: label: Footer sidebar: label: Sidebar widget: elsewhere: label: Find Authors Elsewhere Action: label: Authors Action Stream widgetset: 2column_layout_sidebar: label: 2-column layout - Sidebar widgets: - Find Authors Elsewhere upgrade_functions: enable_existing_streams: version_limit: 9 updater: type: author label: 'Enabling default action streams for selected profiles...' code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams reclass_actions: version_limit: 15 handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions priority: 8 rename_action_metadata: version_limit: 15 handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata priority: 9 upgrade_data: reclass_actions: twitter_tweets: twitter_statuses pownce_notes: pownce_statuses googlereader_shared: googlereader_links rename_action_metadata: - action_type: delicious_links old: annotation new: note - action_type: googlereader_links old: annotation new: note profile_services: services.yaml action_streams: streams.yaml diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm index c92a0ae..b1de43b 100644 --- a/plugins/ActionStreams/lib/ActionStreams/Event.pm +++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm @@ -1,559 +1,577 @@ package ActionStreams::Event; use strict; use base qw( MT::Object MT::Taggable MT::Scorable ); our @EXPORT_OK = qw( classes_for_type ); use HTTP::Date qw( str2time ); use MT::Util qw( encode_html ); use ActionStreams::Scraper; our $hide_timeless = 0; __PACKAGE__->install_properties({ column_defs => { id => 'integer not null auto_increment', identifier => 'string(200)', author_id => 'integer not null', visible => 'integer not null', }, defaults => { visible => 1, }, indexes => { identifier => 1, author_id => 1, created_on => 1, created_by => 1, }, class_type => 'event', audit => 1, meta => 1, datasource => 'profileevent', primary_key => 'id', }); __PACKAGE__->install_meta({ columns => [ qw( title url thumbnail via via_id ) ], }); +# Oracle does not like an identifier of more than 30 characters. +sub datasource { + my $class = shift; + my $r = MT->request; + my $ds = $r->cache('as_event_ds'); + return $ds if $ds; + my $dss_oracle = qr/(db[id]::)?oracle/; + if ( my $type = MT->config('ObjectDriver') ) { + if ((lc $type) =~ m/^$dss_oracle$/) { + $ds = 'as'; + } + } + $ds = $class->properties->{datasource} + unless $ds; + $r->cache('as_event_ds', $ds); + return $ds; +} + sub encode_field_for_html { my $event = shift; my ($field) = @_; return encode_html( $event->$field() ); } sub as_html { my $event = shift; my %params = @_; my $stream = $event->registry_entry or return ''; # How many spaces are there in the form? my $form = $params{form} || $stream->{html_form} || q{}; my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg; my $max = shift @nums; for my $num (@nums) { $max = $num if $max < $num; } # Do we need to supply the author name? my @content = map { $event->encode_field_for_html($_) } @{ $stream->{html_params} }; if ($max > scalar @content) { my $name = defined $params{name} ? $params{name} : $event->author->nickname ; unshift @content, encode_html($name); } return MT->translate($form, @content); } sub update_events_safely { my $class = shift; my %profile = @_; # Keep this option out of band so we don't have to count on # implementations of update_events() passing it through. local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0; my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] }; local $SIG{__WARN__} = sub { my ($msg) = @_; $msg =~ s{ \n \z }{}xms; $msg = MT->component('ActionStreams')->translate( '[_1] updating [_2] events for [_3]', $msg, $profile{type}, $profile{author}->name, ); $warn->("$msg\n"); }; eval { $class->update_events(%profile); }; if (my $err = $@) { my $plugin = MT->component('ActionStreams'); my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]", $profile{author}->name, $class->properties->{class_type}, $profile{type}, $profile{ident}, $err); MT->log($err_msg); die $err; # re-throw so we can handle from job invocation } } sub update_events { my $class = shift; my %profile = @_; my $author = delete $profile{author}; my $stream = $class->registry_entry or return; my $fetch = $stream->{fetch} || {}; local $profile{url} = $stream->{url}; die "Oops, no url?" if !$profile{url}; die "Oops, no ident?" if !$profile{ident}; $profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge; my $items; if (my $xpath_params = $stream->{xpath}) { $items = $class->fetch_xpath( %$xpath_params, %$fetch, %profile, ); } elsif (my $atom_params = $stream->{atom}) { my $get = { created_on => 'published', modified_on => 'updated', title => 'title', url => q{link[@rel='alternate']/@href}, via => q{link[@rel='alternate']/@href}, via_id => 'id', identifier => 'id', }; $atom_params = {} if !ref $atom_params; @$get{keys %$atom_params} = values %$atom_params; $items = $class->fetch_xpath( foreach => '//entry', get => $get, %$fetch, %profile ); for my $item (@$items) { if ($item->{modified_on} && !$item->{created_on}) { $item->{created_on} = $item->{modified_on}; } } } elsif (my $rss_params = $stream->{rss}) { my $get = { title => 'title', url => 'link', via => 'link', created_on => 'pubDate', thumbnail => 'media:thumbnail/@url', via_id => 'guid', identifier => 'guid', }; $rss_params = {} if !ref $rss_params; @$get{keys %$rss_params} = values %$rss_params; $items = $class->fetch_xpath( foreach => '//item', get => $get, %$fetch, %profile ); for my $item (@$items) { if ($item->{modified_on} && !$item->{created_on}) { $item->{created_on} = $item->{modified_on}; } } } elsif (my $scraper_params = $stream->{scraper}) { my ($foreach, $get) = @$scraper_params{qw( foreach get )}; my $scraper = scraper { process $foreach, 'res[]' => scraper { while (my ($field, $sel) = each %$get) { process $sel->[0], $field => $sel->[1]; } }; result 'res'; }; $items = $class->fetch_scraper( scraper => $scraper, %$fetch, %profile, ); } return if !$items; $class->build_results( items => $items, stream => $stream, author => $author, profile => \%profile, ); } sub registry_entry { my $event = shift; my ($type, $stream) = split /_/, $event->properties->{class_type}, 2; my $reg = MT->instance->registry('action_streams') or return; my $service = $reg->{$type} or return; $service->{$stream}; } sub author { my $event = shift; my $author_id = $event->author_id or return; return MT->instance->model('author')->lookup($author_id); } sub blog_id { 0 } sub classes_for_type { my $class = shift; my ($type) = @_; my $prevts = MT->instance->registry('action_streams'); my $prevt = $prevts->{$type}; return if !$prevt; my @classes; PACKAGE: while (my ($stream_id, $stream) = each %$prevt) { next if 'HASH' ne ref $stream; next if !$stream->{class} && !$stream->{url}; my $pkg; if ($pkg = $stream->{class}) { $pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms; if (!eval { $pkg->properties }) { if (!eval "require $pkg; 1") { my $error = $@ || q{}; my $pl = MT->component('ActionStreams'); MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]', $pkg, $type, $stream_id, $error)); next PACKAGE; } } } else { $pkg = join q{::}, $class, 'Auto', ucfirst $type, ucfirst $stream_id; if (!eval { $pkg->properties }) { eval "package $pkg; use base qw( $class ); 1" or next; my $class_type = join q{_}, $type, $stream_id; $pkg->install_properties({ class_type => $class_type }); $pkg->install_meta({ columns => $stream->{fields} }) if $stream->{fields}; } } push @classes, $pkg; } return @classes; } my $ua; sub ua { my $class = shift; my %params = @_; $ua ||= MT->new_ua({ paranoid => 1, timeout => 10, }); $ua->max_size(250_000) if $ua->can('max_size'); $ua->agent($params{default_useragent} ? $ua->_agent : "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version); return $ua if $class->class_type eq 'event'; require ActionStreams::UserAgent::Adapter; my $adapter = ActionStreams::UserAgent::Adapter->new( ua => $ua, action_type => $class->class_type, ); return $adapter; } sub set_values { my $event = shift; my ($values) = @_; for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) { my $meta_val = delete $values->{$meta_col}; $event->$meta_col($meta_val) if defined $meta_val; } $event->SUPER::set_values($values); } sub fetch_xpath { my $class = shift; my %params = @_; my $url = $params{url} || ''; if (!$url) { MT->log("No URL to fetch for $class results"); return; } my $ua = $class->ua(%params); my $res = $ua->get($url); if (!$res->is_success()) { MT->log("Could not fetch ${url}: " . $res->status_line()) if $res->code != 304; return; } # Strip leading whitespace, since the parser doesn't like it. # TODO: confirm we got xml? my $content = $res->content; $content =~ s{ \A \s+ }{}xms; require XML::XPath; my $x = XML::XPath->new( xml => $content ); my @items; ITEM: for my $item ($x->findnodes($params{foreach})) { my %item_data; VALUE: while (my ($key, $val) = each %{ $params{get} }) { next VALUE if !$val; if ($key eq 'tags') { my @outvals = $item->findnodes($val) or next VALUE; $item_data{$key} = [ map { $_->getNodeValue } @outvals ]; } else { my $outval = $item->findvalue($val) or next VALUE; $outval = "$outval"; if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) { # try both RFC 822/1123 and ISO 8601 formats $outval = MT::Util::epoch2ts(undef, str2time($outval)) || MT::Util::iso2ts(undef, $outval); } $item_data{$key} = $outval if $outval; } } push @items, \%item_data; } return \@items; } sub build_results { my $class = shift; my %params = @_; my ($author, $items, $profile, $stream) = @params{qw( author items profile stream )}; my $mt = MT->app; ITEM: for my $item (@$items) { my $event; my $identifier = delete $item->{identifier}; if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) { $identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} }; } if (defined $identifier) { $identifier = "$identifier"; ($event) = $class->search({ author_id => $author->id, identifier => $identifier, }); } $event ||= $class->new; $mt->run_callbacks('pre_build_action_streams_event.' . $class->class_type, $mt, $item, $event, $author, $profile); my $tags = delete $item->{tags}; $event->set_values({ author_id => $author->id, identifier => $identifier, %$item, }); $event->tags(@$tags) if $tags; if ($hide_timeless && !$event->created_on) { $event->visible(0); } $mt->run_callbacks('post_build_action_streams_event.' . $class->class_type, $mt, $item, $event, $author, $profile); $event->save() or MT->log($event->errstr); } 1; } sub save { my $event = shift; # Built-in audit field setting will set a local time, so do it ourselves. if (!$event->created_on) { my $ts = MT::Util::epoch2ts(undef, time); $event->created_on($ts); $event->modified_on($ts); } return $event->SUPER::save(@_); } sub fetch_scraper { my $class = shift; my %params = @_; my ($url, $scraper) = @params{qw( url scraper )}; $scraper->user_agent($class->ua(%params)); my $items = $scraper->scrape(URI->new($url)); # we're only being used for our scraper. return if !$items; return $items if !ref $items; return $items if 'ARRAY' ne ref $items; ITEM: for my $item (@$items) { next ITEM if !ref $item || ref $item ne 'HASH'; for my $field (keys %$item) { if ($field eq 'tags') { $item->{$field} = [ map { "$_" } @{ $item->{$field} } ]; } else { $item->{$field} = q{} . $item->{$field}; } } } return $items; } 1; __END__ =head1 NAME ActionStreams::Event - an Action Streams stream definition =head1 SYNOPSIS # in plugin's config.yaml profile_services: example: streamid: name: Dice Example description: A simple die rolling Perl stream example. html_form: [_1] rolled a [_2]! html_params: - title class: My::Stream # in plugin's lib/My/Stream.pm package My::Stream; use base qw( ActionStreams::Event ); __PACKAGE__->install_properties({ class_type => 'example_streamid', }); sub update_events { my $class = shift; my %profile = @_; # trivial example: save a random number my $die_roll = int rand 20; my %item = ( title => $die_roll, identifier => $die_roll, ); return $class->build_results( author => $profile{author}, items => [ \%item ], ); } 1; =head1 DESCRIPTION I<ActionStreams::Event> provides the basic implementation of an action stream. Stream definitions are engines for turning web resources into I<actions> (also called I<events>). This base class produces actions based on generic stream recipes defined in the MT registry, as well as providing the internal machinery for you to implement your own streams in Perl code. =head1 METHODS TO IMPLEMENT These are the methods one commonly implements (overrides) when implementing a stream subclass. =head2 C<$class-E<GT>update_events(%profile)> Fetches the web resource specified by the profile parameters, collects data from it into actions, and saves the action records for use later. Required members of C<%profile> are: =over 4 =item * C<author> The C<MT::Author> instance for whom events should be collected. =item * C<ident> The author's identifier on the given service. =back Other information about the stream, such as the URL pattern into which the C<ident> parameter can be replaced, is available through the C<$class-E<gt>registry_entry()> method. =head2 C<$self-E<GT>as_html(%params)> Returns the HTML version of the action, suitable for display to readers. The default implementation uses the stream's registry definition to construct the action: the author's name and the action's values as named in C<html_params> are replaced into the stream's C<html_form> setting. You need override it only if you have more complex requirements. Optional members of C<%params> are: =over 4 =item * C<form> The formatting string to use. If not given, the C<html_form> specified for this stream in the registry is used. =item * C<name>
markpasc/mt-plugin-action-streams
cc781784c9bbccf0de53f52b92ffe6a83ec2cd05
Fixed BugID:89294 * Added actionstreams_pre_search callback that do call before search for ActionStreams::Event
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm index 418dace..76c8f1e 100644 --- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm +++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm @@ -1,464 +1,465 @@ package ActionStreams::Tags; use strict; use MT::Util qw( offset_time_list epoch2ts ts2epoch ); use ActionStreams::Plugin; sub stream_action { my ($ctx, $args, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamAction in a non-action-stream context!"); return $event->as_html( defined $args->{name} ? (name => $args->{name}) : () ); } sub stream_action_id { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); return $event->id || ''; } sub stream_action_var { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVar in a non-action-stream context!"); my $var = $arg->{var} || $arg->{name} or return $ctx->error("Used StreamActionVar without a 'name' attribute!"); return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event) if !$event->can($var) && !$event->has_column($var); return $event->$var(); } sub stream_action_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionDate in a non-action-stream context!"); my $c_on = $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) ) if $c_on; return $ctx->_hdlr_date($arg); } sub stream_action_modified_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!"); my $m_on = $event->modified_on || $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) ) if $m_on; return $ctx->_hdlr_date($arg); } sub stream_action_title { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionTitle in a non-action-stream context!"); return $event->title || ''; } sub stream_action_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); return $event->url || ''; } sub stream_action_thumbnail_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!"); return $event->thumbnail || ''; } sub stream_action_via { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVia in a non-action-stream context!"); return $event->via || q{}; } sub other_profile_var { my( $ctx, $args ) = @_; my $profile = $ctx->stash( 'other_profile' ) or return $ctx->error( 'No profile defined in ProfileVar' ); my $var = $args->{name} || 'uri'; return defined $profile->{ $var } ? $profile->{ $var } : ''; } sub _author_ids_for_args { my ($ctx, $args, $cond) = @_; my @author_ids; if (my $ids = $args->{author_ids} || $args->{author_id}) { @author_ids = split /\s*,\s*/, $ids; } elsif (my $disp_names = $args->{display_names} || $args->{display_name}) { my @names = split /\s*,\s*/, $disp_names; my @authors = MT->model('author')->load({ nickname => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $names = $args->{author} || $args->{authors}) { # If arg is the special string 'all', then include all authors by returning undef instead of an empty array. return if $names =~ m{ \A\s* all \s*\z }xmsi; my @names = split /\s*,\s*/, $names; my @authors = MT->model('author')->load({ name => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $author = $ctx->stash('author')) { @author_ids = ( $author->id ); } elsif (my $blog = $ctx->stash('blog')) { my @authors = MT->model('author')->load({ status => 1, # enabled }, { join => MT->model('permission')->join_on('author_id', { blog_id => $blog->id }, { unique => 1 }), }); @author_ids = map { $_->[0]->id } grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post } map { [ $_, $_->permissions($blog->id) ] } @authors; } return \@author_ids; } sub action_streams { my ($ctx, $args, $cond) = @_; my %terms = ( class => '*', visible => 1, ); my $author_id = _author_ids_for_args(@_); $terms{author_id} = $author_id if defined $author_id; my %args = ( sort => ($args->{sort_by} || 'created_on'), direction => ($args->{direction} || 'descend'), ); my $app = MT->app; undef $app unless $app->isa('MT::App'); if (my $limit = $args->{limit} || $args->{lastn}) { $args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit; } elsif (my $days = $args->{days}) { my @ago = offset_time_list(time - 3600 * 24 * $days, $ctx->stash('blog')); my $ago = sprintf "%04d%02d%02d%02d%02d%02d", $ago[5]+1900, $ago[4]+1, @ago[3,2,1,0]; $terms{created_on} = [ $ago ]; $args{range_incl}{created_on} = 1; } else { $args{limit} = 20; } if (my $offset = $args->{offset}) { if ($offset eq 'auto') { $args{offset} = $app->param('offset') if $app && $app->param('offset') > 0; } elsif ($offset =~ m/^\d+$/) { $args{offset} = $offset; } } my ($service, $stream) = @$args{qw( service stream )}; if ($service && $stream) { $terms{class} = join q{_}, $service, $stream; } elsif ($service) { $terms{class} = $service . '_%'; $args{like} = { class => 1 }; } elsif ($stream) { $terms{class} = '%_' . $stream; $args{like} = { class => 1 }; } # Make sure all classes are loaded. require ActionStreams::Event; for my $service (keys %{ MT->instance->registry('action_streams') || {} }) { ActionStreams::Event->classes_for_type($service); } + $app->run_callbacks('actionstreams_pre_search', \%terms, \%args ); my @events = ActionStreams::Event->search(\%terms, \%args); return $ctx->_hdlr_pass_tokens_else($args, $cond) if !@events; if ($args{sort} eq 'created_on') { @events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events; @events = reverse @events if $args{direction} ne 'descend'; } local $ctx->{__stash}{remaining_stream_actions} = \@events; my $res = ''; my ($count, $total) = (0, scalar @events); my $day_date = ''; EVENT: while (my $event = shift @events) { my $new_day_date = _event_day($ctx, $event); local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0; local $cond->{DateFooter} = !@events ? 1 : $new_day_date ne _event_day($ctx, $events[0]) ? 1 : 0 ; $day_date = $new_day_date; $count++; defined (my $out = _build_about_event( $ctx, $args, $cond, event => $event, count => $count, total => $total, )) or return; $res .= $out; } return $res; } sub _build_about_event { my ($ctx, $arg, $cond, %param) = @_; my ($event, $count, $total) = @param{qw( event count total )}; local $ctx->{__stash}{stream_action} = $event; my $author = $event->author; local $ctx->{__stash}{author} = $event->author; my $type = $event->class_type; my ($service, $stream_id) = split /_/, $type, 2; my $profile = $author->other_profiles($service); next EVENT if !$profile; local $ctx->{__stash}{other_profile} = $profile; my $vars = $ctx->{__stash}{vars} ||= {}; local $vars->{action_type} = $type; local $vars->{service_type} = $service; local $vars->{stream_type} = $stream_id; local $vars->{__first__} = $count == 1; local $vars->{__last__} = $count == $total; local $vars->{__odd__} = ($count % 2) == 1; local $vars->{__even__} = ($count % 2) == 0; local $vars->{__counter__} = $count; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); return $out; } sub stream_action_rollup { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionRollup in a non-action-stream context!"); my $nexts = $ctx->stash('remaining_stream_actions'); return $ctx->else($arg, $cond) if !$nexts || !@$nexts; my $by_spec = $arg->{by} || 'date,action'; my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec; my $event_date = _event_day($ctx, $event); my $event_class = $event->class; my ($event_service, $event_stream) = split /_/, $event_class, 2; my @rollup_events = ($event); EVENT: while (@$nexts) { my $next = $nexts->[0]; last EVENT if $by{date} && $event_date ne _event_day($ctx, $next); last EVENT if $by{action} && $event_class ne $next->class; last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms; last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms; # Eligible to roll up! Remove it from the remaining actions. push @rollup_events, shift @$nexts; } return $ctx->else($arg, $cond) if 1 >= scalar @rollup_events; my $res; my $count = 0; for my $rup_event (@rollup_events) { $count++; defined (my $out = _build_about_event( $ctx, $arg, $cond, event => $rup_event, count => $count, total => scalar @rollup_events, )) or return; $res .= $arg->{glue} if $arg->{glue} && $count > 1; $res .= $out; } return $res; } sub _event_day { my ($ctx, $event) = @_; return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8); } sub stream_action_tags { my ($ctx, $args, $cond) = @_; require MT::Entry; my $event = $ctx->stash('stream_action'); return '' unless $event; my $glue = $args->{glue} || ''; local $ctx->{__stash}{tag_max_count} = undef; local $ctx->{__stash}{tag_min_count} = undef; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = ''; my $tags = $event->get_tag_objects; for my $tag (@$tags) { next if $tag->is_private && !$args->{include_private}; local $ctx->{__stash}{Tag} = $tag; local $ctx->{__stash}{tag_count} = undef; local $ctx->{__stash}{tag_event_count} = undef; # ? defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error( $builder->errstr ); $res .= $glue if $res ne ''; $res .= $out; } $res; } sub other_profiles { my( $ctx, $args, $cond ) = @_; my $author_ids = _author_ids_for_args(@_); my $author_id = shift @$author_ids or return $ctx->error('No author specified for OtherProfiles'); my $user = MT->model('author')->load($author_id) or return $ctx->error(MT->trans('No user [_1]', $author_id)); my @profiles = sort { lc $a->{type} cmp lc $b->{type} } @{ $user->other_profiles() }; my $services = MT->app->registry('profile_services'); if (my $filter_type = $args->{type}) { my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0; @profiles = grep { my $profile = $_; my $profile_type = $profile->{type}; my $service_type = ($services->{$profile_type} || {})->{service_type} || q{}; $filter_except ? $service_type ne $filter_type : $service_type eq $filter_type; } @profiles; } my $populate_icon = sub { my ($item, $row) = @_; my $type = $item->{type}; $row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type}); }; return list( context => $ctx, arguments => $args, conditions => $cond, items => \@profiles, stash_key => 'other_profile', code => $populate_icon, ); } sub list { my %param = @_; my ($ctx, $args, $cond) = @param{qw( context arguments conditions )}; my ($items, $stash_key, $code) = @param{qw( items stash_key code )}; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = q{}; my $glue = $args->{glue}; $glue = '' unless defined $glue; my $vars = ($ctx->{__stash}{vars} ||= {}); my ($count, $total) = (0, scalar @$items); for my $item (@$items) { local $ctx->{__stash}->{$stash_key} = $item; my $row = {}; $code->($item, $row) if $code; my $lvars = delete $row->{vars} if exists $row->{vars}; local @$vars{keys %$lvars} = values %$lvars if $lvars; local @{ $ctx->{__stash} }{keys %$row} = values %$row; $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; defined (my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); $res .= $glue if ($res ne '') && ($out ne '') && ($glue ne ''); $res .= $out; } return $res; } sub profile_services { my( $ctx, $args, $cond ) = @_; my $app = MT->app; my $networks = $app->registry('profile_services'); my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} } keys %$networks; my $out = ""; my $builder = $ctx->stash( 'builder' ); my $tokens = $ctx->stash( 'tokens' ); my $vars = ($ctx->{__stash}{vars} ||= {}); if ($args->{extra}) { # Skip output completely if it's a "core" service but we want # extras only. @network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys; } my ($count, $total) = (0, scalar @network_keys); for my $type (@network_keys) { $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; my $ndata = $networks->{$type}; local @$vars{keys %$ndata} = values %$ndata; local $vars->{label} = $ndata->{name}; local $vars->{type} = $type; local $vars->{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $networks->{$type}); local $ctx->{__stash}{profile_service} = $ndata; $out .= $builder->build( $ctx, $tokens, $cond ); } return $out; } 1;
markpasc/mt-plugin-action-streams
663b23adab45b9602c5179888fc81626eb48018e
Create StreamActionID tag for feed. BugzID:89133
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml index 0448c44..8733dc9 100644 --- a/plugins/ActionStreams/config.yaml +++ b/plugins/ActionStreams/config.yaml @@ -1,182 +1,183 @@ name: Action Streams id: ActionStreams key: ActionStreams author_link: http://www.sixapart.com/ author_name: Six Apart Ltd. description: Manages authors' accounts and actions on sites elsewhere around the web schema_version: 16 version: 2.0 plugin_link: http://www.sixapart.com/ settings: rebuild_for_action_stream_events: Default: 0 Scope: blog blog_config_template: blog_config_template.tmpl init_app: $ActionStreams::ActionStreams::Init::init_app applications: cms: methods: list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events community: methods: profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile callbacks: post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events callbacks: MT::App::CMS::template_source.users_content_nav: $ActionStreams::ActionStreams::Plugin::users_content_nav MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb object_types: profileevent: ActionStreams::Event as_ua_cache: ActionStreams::UserAgent::Cache list_actions: profileevent: hide_all: label: Hide All order: 100 js: finishPluginActionAll code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events continue_prompt: 'Are you sure you want to hide EVERY event in EVERY action stream?' show_all: label: Show All order: 200 js: finishPluginActionAll code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events continue_prompt: 'Are you sure you want to show EVERY event in EVERY action stream?' delete: label: Delete order: 300 code: $core::MT::App::CMS::delete continue_prompt: 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' tags: function: StreamAction: $ActionStreams::ActionStreams::Tags::stream_action + StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var block: ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup tasks: UpdateEvents: frequency: 1800 label: Poll for new events code: $ActionStreams::ActionStreams::Plugin::update_events task_workers: UpdateEvents: label: Update Events class: ActionStreams::Worker widgets: asotd: label: Recent Actions template: widget_recent.mtml permission: post singular: 1 set: sidebar handler: $ActionStreams::ActionStreams::Plugin::widget_recent condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only template_sets: streams: label: 'Action Stream' base_path: 'blog_tmpl' order: 100 templates: index: main_index: label: Main Index (Recent Actions) outfile: index.html rebuild_me: 1 archive: label: Action Archive outfile: archive.html rebuild_me: 1 styles: label: Stylesheet outfile: styles.css rebuild_me: 1 atom: label: Atom outfile: atom.xml rebuild_me: 1 module: header: label: Header footer: label: Footer sidebar: label: Sidebar widget: elsewhere: label: Find Authors Elsewhere Action: label: Authors Action Stream widgetset: 2column_layout_sidebar: label: 2-column layout - Sidebar widgets: - Find Authors Elsewhere upgrade_functions: enable_existing_streams: version_limit: 9 updater: type: author label: 'Enabling default action streams for selected profiles...' code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams reclass_actions: version_limit: 15 handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions priority: 8 rename_action_metadata: version_limit: 15 handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata priority: 9 upgrade_data: reclass_actions: twitter_tweets: twitter_statuses pownce_notes: pownce_statuses googlereader_shared: googlereader_links rename_action_metadata: - action_type: delicious_links old: annotation new: note - action_type: googlereader_links old: annotation new: note profile_services: services.yaml action_streams: streams.yaml diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm index 475fe42..418dace 100644 --- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm +++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm @@ -1,457 +1,464 @@ package ActionStreams::Tags; use strict; use MT::Util qw( offset_time_list epoch2ts ts2epoch ); use ActionStreams::Plugin; sub stream_action { my ($ctx, $args, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamAction in a non-action-stream context!"); return $event->as_html( defined $args->{name} ? (name => $args->{name}) : () ); } +sub stream_action_id { + my ($ctx, $arg, $cond) = @_; + my $event = $ctx->stash('stream_action') + or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); + return $event->id || ''; +} + sub stream_action_var { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVar in a non-action-stream context!"); my $var = $arg->{var} || $arg->{name} or return $ctx->error("Used StreamActionVar without a 'name' attribute!"); return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event) if !$event->can($var) && !$event->has_column($var); return $event->$var(); } sub stream_action_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionDate in a non-action-stream context!"); my $c_on = $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) ) if $c_on; return $ctx->_hdlr_date($arg); } sub stream_action_modified_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!"); my $m_on = $event->modified_on || $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) ) if $m_on; return $ctx->_hdlr_date($arg); } sub stream_action_title { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionTitle in a non-action-stream context!"); return $event->title || ''; } sub stream_action_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); return $event->url || ''; } sub stream_action_thumbnail_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!"); return $event->thumbnail || ''; } sub stream_action_via { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVia in a non-action-stream context!"); return $event->via || q{}; } sub other_profile_var { my( $ctx, $args ) = @_; my $profile = $ctx->stash( 'other_profile' ) or return $ctx->error( 'No profile defined in ProfileVar' ); my $var = $args->{name} || 'uri'; return defined $profile->{ $var } ? $profile->{ $var } : ''; } sub _author_ids_for_args { my ($ctx, $args, $cond) = @_; my @author_ids; if (my $ids = $args->{author_ids} || $args->{author_id}) { @author_ids = split /\s*,\s*/, $ids; } elsif (my $disp_names = $args->{display_names} || $args->{display_name}) { my @names = split /\s*,\s*/, $disp_names; my @authors = MT->model('author')->load({ nickname => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $names = $args->{author} || $args->{authors}) { # If arg is the special string 'all', then include all authors by returning undef instead of an empty array. return if $names =~ m{ \A\s* all \s*\z }xmsi; my @names = split /\s*,\s*/, $names; my @authors = MT->model('author')->load({ name => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $author = $ctx->stash('author')) { @author_ids = ( $author->id ); } elsif (my $blog = $ctx->stash('blog')) { my @authors = MT->model('author')->load({ status => 1, # enabled }, { join => MT->model('permission')->join_on('author_id', { blog_id => $blog->id }, { unique => 1 }), }); @author_ids = map { $_->[0]->id } grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post } map { [ $_, $_->permissions($blog->id) ] } @authors; } return \@author_ids; } sub action_streams { my ($ctx, $args, $cond) = @_; my %terms = ( class => '*', visible => 1, ); my $author_id = _author_ids_for_args(@_); $terms{author_id} = $author_id if defined $author_id; my %args = ( sort => ($args->{sort_by} || 'created_on'), direction => ($args->{direction} || 'descend'), ); my $app = MT->app; undef $app unless $app->isa('MT::App'); if (my $limit = $args->{limit} || $args->{lastn}) { $args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit; } elsif (my $days = $args->{days}) { my @ago = offset_time_list(time - 3600 * 24 * $days, $ctx->stash('blog')); my $ago = sprintf "%04d%02d%02d%02d%02d%02d", $ago[5]+1900, $ago[4]+1, @ago[3,2,1,0]; $terms{created_on} = [ $ago ]; $args{range_incl}{created_on} = 1; } else { $args{limit} = 20; } if (my $offset = $args->{offset}) { if ($offset eq 'auto') { $args{offset} = $app->param('offset') if $app && $app->param('offset') > 0; } elsif ($offset =~ m/^\d+$/) { $args{offset} = $offset; } } my ($service, $stream) = @$args{qw( service stream )}; if ($service && $stream) { $terms{class} = join q{_}, $service, $stream; } elsif ($service) { $terms{class} = $service . '_%'; $args{like} = { class => 1 }; } elsif ($stream) { $terms{class} = '%_' . $stream; $args{like} = { class => 1 }; } # Make sure all classes are loaded. require ActionStreams::Event; for my $service (keys %{ MT->instance->registry('action_streams') || {} }) { ActionStreams::Event->classes_for_type($service); } my @events = ActionStreams::Event->search(\%terms, \%args); return $ctx->_hdlr_pass_tokens_else($args, $cond) if !@events; if ($args{sort} eq 'created_on') { @events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events; @events = reverse @events if $args{direction} ne 'descend'; } local $ctx->{__stash}{remaining_stream_actions} = \@events; my $res = ''; my ($count, $total) = (0, scalar @events); my $day_date = ''; EVENT: while (my $event = shift @events) { my $new_day_date = _event_day($ctx, $event); local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0; local $cond->{DateFooter} = !@events ? 1 : $new_day_date ne _event_day($ctx, $events[0]) ? 1 : 0 ; $day_date = $new_day_date; $count++; defined (my $out = _build_about_event( $ctx, $args, $cond, event => $event, count => $count, total => $total, )) or return; $res .= $out; } return $res; } sub _build_about_event { my ($ctx, $arg, $cond, %param) = @_; my ($event, $count, $total) = @param{qw( event count total )}; local $ctx->{__stash}{stream_action} = $event; my $author = $event->author; local $ctx->{__stash}{author} = $event->author; my $type = $event->class_type; my ($service, $stream_id) = split /_/, $type, 2; my $profile = $author->other_profiles($service); next EVENT if !$profile; local $ctx->{__stash}{other_profile} = $profile; my $vars = $ctx->{__stash}{vars} ||= {}; local $vars->{action_type} = $type; local $vars->{service_type} = $service; local $vars->{stream_type} = $stream_id; local $vars->{__first__} = $count == 1; local $vars->{__last__} = $count == $total; local $vars->{__odd__} = ($count % 2) == 1; local $vars->{__even__} = ($count % 2) == 0; local $vars->{__counter__} = $count; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); return $out; } sub stream_action_rollup { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionRollup in a non-action-stream context!"); my $nexts = $ctx->stash('remaining_stream_actions'); return $ctx->else($arg, $cond) if !$nexts || !@$nexts; my $by_spec = $arg->{by} || 'date,action'; my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec; my $event_date = _event_day($ctx, $event); my $event_class = $event->class; my ($event_service, $event_stream) = split /_/, $event_class, 2; my @rollup_events = ($event); EVENT: while (@$nexts) { my $next = $nexts->[0]; last EVENT if $by{date} && $event_date ne _event_day($ctx, $next); last EVENT if $by{action} && $event_class ne $next->class; last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms; last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms; # Eligible to roll up! Remove it from the remaining actions. push @rollup_events, shift @$nexts; } return $ctx->else($arg, $cond) if 1 >= scalar @rollup_events; my $res; my $count = 0; for my $rup_event (@rollup_events) { $count++; defined (my $out = _build_about_event( $ctx, $arg, $cond, event => $rup_event, count => $count, total => scalar @rollup_events, )) or return; $res .= $arg->{glue} if $arg->{glue} && $count > 1; $res .= $out; } return $res; } sub _event_day { my ($ctx, $event) = @_; return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8); } sub stream_action_tags { my ($ctx, $args, $cond) = @_; require MT::Entry; my $event = $ctx->stash('stream_action'); return '' unless $event; my $glue = $args->{glue} || ''; local $ctx->{__stash}{tag_max_count} = undef; local $ctx->{__stash}{tag_min_count} = undef; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = ''; my $tags = $event->get_tag_objects; for my $tag (@$tags) { next if $tag->is_private && !$args->{include_private}; local $ctx->{__stash}{Tag} = $tag; local $ctx->{__stash}{tag_count} = undef; local $ctx->{__stash}{tag_event_count} = undef; # ? defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error( $builder->errstr ); $res .= $glue if $res ne ''; $res .= $out; } $res; } sub other_profiles { my( $ctx, $args, $cond ) = @_; my $author_ids = _author_ids_for_args(@_); my $author_id = shift @$author_ids or return $ctx->error('No author specified for OtherProfiles'); my $user = MT->model('author')->load($author_id) or return $ctx->error(MT->trans('No user [_1]', $author_id)); my @profiles = sort { lc $a->{type} cmp lc $b->{type} } @{ $user->other_profiles() }; my $services = MT->app->registry('profile_services'); if (my $filter_type = $args->{type}) { my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0; @profiles = grep { my $profile = $_; my $profile_type = $profile->{type}; my $service_type = ($services->{$profile_type} || {})->{service_type} || q{}; $filter_except ? $service_type ne $filter_type : $service_type eq $filter_type; } @profiles; } my $populate_icon = sub { my ($item, $row) = @_; my $type = $item->{type}; $row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type}); }; return list( context => $ctx, arguments => $args, conditions => $cond, items => \@profiles, stash_key => 'other_profile', code => $populate_icon, ); } sub list { my %param = @_; my ($ctx, $args, $cond) = @param{qw( context arguments conditions )}; my ($items, $stash_key, $code) = @param{qw( items stash_key code )}; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = q{}; my $glue = $args->{glue}; $glue = '' unless defined $glue; my $vars = ($ctx->{__stash}{vars} ||= {}); my ($count, $total) = (0, scalar @$items); for my $item (@$items) { local $ctx->{__stash}->{$stash_key} = $item; my $row = {}; $code->($item, $row) if $code; my $lvars = delete $row->{vars} if exists $row->{vars}; local @$vars{keys %$lvars} = values %$lvars if $lvars; local @{ $ctx->{__stash} }{keys %$row} = values %$row; $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; defined (my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); $res .= $glue if ($res ne '') && ($out ne '') && ($glue ne ''); $res .= $out; } return $res; } sub profile_services { my( $ctx, $args, $cond ) = @_; my $app = MT->app; my $networks = $app->registry('profile_services'); my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} } keys %$networks; my $out = ""; my $builder = $ctx->stash( 'builder' ); my $tokens = $ctx->stash( 'tokens' ); my $vars = ($ctx->{__stash}{vars} ||= {}); if ($args->{extra}) { # Skip output completely if it's a "core" service but we want # extras only. @network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys; } my ($count, $total) = (0, scalar @network_keys); for my $type (@network_keys) { $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; my $ndata = $networks->{$type}; local @$vars{keys %$ndata} = values %$ndata; local $vars->{label} = $ndata->{name}; local $vars->{type} = $type; local $vars->{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $networks->{$type}); local $ctx->{__stash}{profile_service} = $ndata; $out .= $builder->build( $ctx, $tokens, $cond ); } return $out; } 1;
markpasc/mt-plugin-action-streams
829a96293ceb9195d522a57f5eb7e49b0da0cc9e
Change to get contributor permission author id also. BugzID:86646
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm index f494946..475fe42 100644 --- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm +++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm @@ -1,457 +1,457 @@ package ActionStreams::Tags; use strict; use MT::Util qw( offset_time_list epoch2ts ts2epoch ); use ActionStreams::Plugin; sub stream_action { my ($ctx, $args, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamAction in a non-action-stream context!"); return $event->as_html( defined $args->{name} ? (name => $args->{name}) : () ); } sub stream_action_var { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVar in a non-action-stream context!"); my $var = $arg->{var} || $arg->{name} or return $ctx->error("Used StreamActionVar without a 'name' attribute!"); return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event) if !$event->can($var) && !$event->has_column($var); return $event->$var(); } sub stream_action_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionDate in a non-action-stream context!"); my $c_on = $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) ) if $c_on; return $ctx->_hdlr_date($arg); } sub stream_action_modified_date { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!"); my $m_on = $event->modified_on || $event->created_on; local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) ) if $m_on; return $ctx->_hdlr_date($arg); } sub stream_action_title { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionTitle in a non-action-stream context!"); return $event->title || ''; } sub stream_action_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionURL in a non-action-stream context!"); return $event->url || ''; } sub stream_action_thumbnail_url { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!"); return $event->thumbnail || ''; } sub stream_action_via { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionVia in a non-action-stream context!"); return $event->via || q{}; } sub other_profile_var { my( $ctx, $args ) = @_; my $profile = $ctx->stash( 'other_profile' ) or return $ctx->error( 'No profile defined in ProfileVar' ); my $var = $args->{name} || 'uri'; return defined $profile->{ $var } ? $profile->{ $var } : ''; } sub _author_ids_for_args { my ($ctx, $args, $cond) = @_; my @author_ids; if (my $ids = $args->{author_ids} || $args->{author_id}) { @author_ids = split /\s*,\s*/, $ids; } elsif (my $disp_names = $args->{display_names} || $args->{display_name}) { my @names = split /\s*,\s*/, $disp_names; my @authors = MT->model('author')->load({ nickname => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $names = $args->{author} || $args->{authors}) { # If arg is the special string 'all', then include all authors by returning undef instead of an empty array. return if $names =~ m{ \A\s* all \s*\z }xmsi; my @names = split /\s*,\s*/, $names; my @authors = MT->model('author')->load({ name => \@names }); @author_ids = map { $_->id } @authors; } elsif (my $author = $ctx->stash('author')) { @author_ids = ( $author->id ); } elsif (my $blog = $ctx->stash('blog')) { my @authors = MT->model('author')->load({ status => 1, # enabled }, { join => MT->model('permission')->join_on('author_id', { blog_id => $blog->id }, { unique => 1 }), }); @author_ids = map { $_->[0]->id } - grep { $_->[1]->can_administer_blog || $_->[1]->can_post } + grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post } map { [ $_, $_->permissions($blog->id) ] } @authors; } return \@author_ids; } sub action_streams { my ($ctx, $args, $cond) = @_; my %terms = ( class => '*', visible => 1, ); my $author_id = _author_ids_for_args(@_); $terms{author_id} = $author_id if defined $author_id; my %args = ( sort => ($args->{sort_by} || 'created_on'), direction => ($args->{direction} || 'descend'), ); my $app = MT->app; undef $app unless $app->isa('MT::App'); if (my $limit = $args->{limit} || $args->{lastn}) { $args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit; } elsif (my $days = $args->{days}) { my @ago = offset_time_list(time - 3600 * 24 * $days, $ctx->stash('blog')); my $ago = sprintf "%04d%02d%02d%02d%02d%02d", $ago[5]+1900, $ago[4]+1, @ago[3,2,1,0]; $terms{created_on} = [ $ago ]; $args{range_incl}{created_on} = 1; } else { $args{limit} = 20; } if (my $offset = $args->{offset}) { if ($offset eq 'auto') { $args{offset} = $app->param('offset') if $app && $app->param('offset') > 0; } elsif ($offset =~ m/^\d+$/) { $args{offset} = $offset; } } my ($service, $stream) = @$args{qw( service stream )}; if ($service && $stream) { $terms{class} = join q{_}, $service, $stream; } elsif ($service) { $terms{class} = $service . '_%'; $args{like} = { class => 1 }; } elsif ($stream) { $terms{class} = '%_' . $stream; $args{like} = { class => 1 }; } # Make sure all classes are loaded. require ActionStreams::Event; for my $service (keys %{ MT->instance->registry('action_streams') || {} }) { ActionStreams::Event->classes_for_type($service); } my @events = ActionStreams::Event->search(\%terms, \%args); return $ctx->_hdlr_pass_tokens_else($args, $cond) if !@events; if ($args{sort} eq 'created_on') { @events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events; @events = reverse @events if $args{direction} ne 'descend'; } local $ctx->{__stash}{remaining_stream_actions} = \@events; my $res = ''; my ($count, $total) = (0, scalar @events); my $day_date = ''; EVENT: while (my $event = shift @events) { my $new_day_date = _event_day($ctx, $event); local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0; local $cond->{DateFooter} = !@events ? 1 : $new_day_date ne _event_day($ctx, $events[0]) ? 1 : 0 ; $day_date = $new_day_date; $count++; defined (my $out = _build_about_event( $ctx, $args, $cond, event => $event, count => $count, total => $total, )) or return; $res .= $out; } return $res; } sub _build_about_event { my ($ctx, $arg, $cond, %param) = @_; my ($event, $count, $total) = @param{qw( event count total )}; local $ctx->{__stash}{stream_action} = $event; my $author = $event->author; local $ctx->{__stash}{author} = $event->author; my $type = $event->class_type; my ($service, $stream_id) = split /_/, $type, 2; my $profile = $author->other_profiles($service); next EVENT if !$profile; local $ctx->{__stash}{other_profile} = $profile; my $vars = $ctx->{__stash}{vars} ||= {}; local $vars->{action_type} = $type; local $vars->{service_type} = $service; local $vars->{stream_type} = $stream_id; local $vars->{__first__} = $count == 1; local $vars->{__last__} = $count == $total; local $vars->{__odd__} = ($count % 2) == 1; local $vars->{__even__} = ($count % 2) == 0; local $vars->{__counter__} = $count; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); return $out; } sub stream_action_rollup { my ($ctx, $arg, $cond) = @_; my $event = $ctx->stash('stream_action') or return $ctx->error("Used StreamActionRollup in a non-action-stream context!"); my $nexts = $ctx->stash('remaining_stream_actions'); return $ctx->else($arg, $cond) if !$nexts || !@$nexts; my $by_spec = $arg->{by} || 'date,action'; my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec; my $event_date = _event_day($ctx, $event); my $event_class = $event->class; my ($event_service, $event_stream) = split /_/, $event_class, 2; my @rollup_events = ($event); EVENT: while (@$nexts) { my $next = $nexts->[0]; last EVENT if $by{date} && $event_date ne _event_day($ctx, $next); last EVENT if $by{action} && $event_class ne $next->class; last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms; last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms; # Eligible to roll up! Remove it from the remaining actions. push @rollup_events, shift @$nexts; } return $ctx->else($arg, $cond) if 1 >= scalar @rollup_events; my $res; my $count = 0; for my $rup_event (@rollup_events) { $count++; defined (my $out = _build_about_event( $ctx, $arg, $cond, event => $rup_event, count => $count, total => scalar @rollup_events, )) or return; $res .= $arg->{glue} if $arg->{glue} && $count > 1; $res .= $out; } return $res; } sub _event_day { my ($ctx, $event) = @_; return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8); } sub stream_action_tags { my ($ctx, $args, $cond) = @_; require MT::Entry; my $event = $ctx->stash('stream_action'); return '' unless $event; my $glue = $args->{glue} || ''; local $ctx->{__stash}{tag_max_count} = undef; local $ctx->{__stash}{tag_min_count} = undef; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = ''; my $tags = $event->get_tag_objects; for my $tag (@$tags) { next if $tag->is_private && !$args->{include_private}; local $ctx->{__stash}{Tag} = $tag; local $ctx->{__stash}{tag_count} = undef; local $ctx->{__stash}{tag_event_count} = undef; # ? defined(my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error( $builder->errstr ); $res .= $glue if $res ne ''; $res .= $out; } $res; } sub other_profiles { my( $ctx, $args, $cond ) = @_; my $author_ids = _author_ids_for_args(@_); my $author_id = shift @$author_ids or return $ctx->error('No author specified for OtherProfiles'); my $user = MT->model('author')->load($author_id) or return $ctx->error(MT->trans('No user [_1]', $author_id)); my @profiles = sort { lc $a->{type} cmp lc $b->{type} } @{ $user->other_profiles() }; my $services = MT->app->registry('profile_services'); if (my $filter_type = $args->{type}) { my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0; @profiles = grep { my $profile = $_; my $profile_type = $profile->{type}; my $service_type = ($services->{$profile_type} || {})->{service_type} || q{}; $filter_except ? $service_type ne $filter_type : $service_type eq $filter_type; } @profiles; } my $populate_icon = sub { my ($item, $row) = @_; my $type = $item->{type}; $row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type}); }; return list( context => $ctx, arguments => $args, conditions => $cond, items => \@profiles, stash_key => 'other_profile', code => $populate_icon, ); } sub list { my %param = @_; my ($ctx, $args, $cond) = @param{qw( context arguments conditions )}; my ($items, $stash_key, $code) = @param{qw( items stash_key code )}; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); my $res = q{}; my $glue = $args->{glue}; $glue = '' unless defined $glue; my $vars = ($ctx->{__stash}{vars} ||= {}); my ($count, $total) = (0, scalar @$items); for my $item (@$items) { local $ctx->{__stash}->{$stash_key} = $item; my $row = {}; $code->($item, $row) if $code; my $lvars = delete $row->{vars} if exists $row->{vars}; local @$vars{keys %$lvars} = values %$lvars if $lvars; local @{ $ctx->{__stash} }{keys %$row} = values %$row; $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; defined (my $out = $builder->build($ctx, $tokens, $cond)) or return $ctx->error($builder->errstr); $res .= $glue if ($res ne '') && ($out ne '') && ($glue ne ''); $res .= $out; } return $res; } sub profile_services { my( $ctx, $args, $cond ) = @_; my $app = MT->app; my $networks = $app->registry('profile_services'); my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} } keys %$networks; my $out = ""; my $builder = $ctx->stash( 'builder' ); my $tokens = $ctx->stash( 'tokens' ); my $vars = ($ctx->{__stash}{vars} ||= {}); if ($args->{extra}) { # Skip output completely if it's a "core" service but we want # extras only. @network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys; } my ($count, $total) = (0, scalar @network_keys); for my $type (@network_keys) { $count++; my %loop_vars = ( __first__ => $count == 1, __last__ => $count == $total, __odd__ => $count % 2, __even__ => !($count % 2), __counter__ => $count, ); local @$vars{keys %loop_vars} = values %loop_vars; my $ndata = $networks->{$type}; local @$vars{keys %$ndata} = values %$ndata; local $vars->{label} = $ndata->{name}; local $vars->{type} = $type; local $vars->{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $networks->{$type}); local $ctx->{__stash}{profile_service} = $ndata; $out .= $builder->build( $ctx, $tokens, $cond ); } return $out; } 1;
markpasc/mt-plugin-action-streams
e5f96fec3778a3a91d0194c57e04b110ab02c5c6
Fixed BugID: 87474 * Hide menus when creating user
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm index fe50dab..bb32a96 100644 --- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm +++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm @@ -1,523 +1,525 @@ package ActionStreams::Plugin; use strict; use warnings; use Carp qw( croak ); use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts ); sub users_content_nav { my ($cb, $app, $html_ref) = @_; + return unless $app->param('id'); + $$html_ref =~ s{class=["']active["']}{}xmsg if $app->mode eq 'list_profileevent' || $app->mode eq 'other_profiles'; $$html_ref =~ m{ "> ((?:<b>)?) <__trans \s phrase="Permissions"> ((?:</b>)?) </a> }xms; my ($open_bold, $close_bold) = ($1, $2); my $html = <<"EOF"; <mt:if var="USER_VIEW"> <li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&amp;id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li> <li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&amp;id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li> </mt:if> <mt:if var="edit_author"> <li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&amp;id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li> <li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&amp;id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li> </mt:if> EOF $$html_ref =~ s{(?=</ul>)}{$html}xmsg; } sub icon_url_for_service { my $class = shift; my ($type, $ndata) = @_; my $plug = $ndata->{plugin} or return; my $icon_url; if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) { $icon_url = $ndata->{icon}; } elsif ($ndata->{icon}) { $icon_url = MT->app->static_path . join q{/}, $plug->envelope, $ndata->{icon}; } elsif ($plug->id eq 'actionstreams') { $icon_url = MT->app->static_path . join q{/}, $plug->envelope, 'images', 'services', $type . '.png'; } return $icon_url; } sub list_profileevent { my $app = shift; my %param = @_; $app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id'); my $author_id = $app->param('id') or return; return $app->error('Not permitted to view') if $app->user->id != $author_id && !$app->user->is_superuser(); my %service_styles; my @service_styles_loop; my $code = sub { my ($event, $row) = @_; my @meta_col = keys %{ $event->properties->{meta_columns} || {} }; $row->{$_} = $event->{$_} for @meta_col; $row->{as_html} = $event->as_html(); my ($service, $stream_id) = split /_/, $row->{class}, 2; $row->{type} = $service; my $nets = $app->registry('profile_services') || {}; my $net = $nets->{$service}; $row->{service} = $net->{name} if $net; $row->{url} = $event->url; if (!$service_styles{$service}) { if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') { if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) { push @service_styles_loop, { service_type => $service, service_icon => $icon, }; } } $service_styles{$service} = 1; } my $ts = $row->{created_on}; $row->{created_on_relative} = relative_date($ts, time); $row->{created_on_formatted} = format_ts( MT::App::CMS->LISTING_DATETIME_FORMAT(), epoch2ts(undef, offset_time(ts2epoch(undef, $ts))), undef, $app->user ? $app->user->preferred_language : undef, ); }; # Make sure all classes are loaded. require ActionStreams::Event; for my $prevt (keys %{ $app->registry('action_streams') }) { ActionStreams::Event->classes_for_type($prevt); } my $plugin = MT->component('ActionStreams'); my %params = map { $_ => $app->param($_) ? 1 : 0 } qw( saved_deleted hidden shown ); $params{services} = []; my $services = $app->registry('profile_services'); while (my ($prevt, $service) = each %$services) { push @{ $params{services} }, { service_id => $prevt, service_name => $service->{name}, }; } $params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ]; my %terms = ( class => '*', author_id => $author_id, ); my %args = ( sort => 'created_on', direction => 'descend', ); if (my $filter = $app->param('filter')) { $params{filter_key} = $filter; my $filter_val = $params{filter_val} = $app->param('filter_val'); if ($filter eq 'service') { $params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name}); $terms{class} = $filter_val . '_%'; $args{like} = { class => 1 }; } elsif ($filter eq 'visible') { $params{filter_label} = ($filter_val eq 'show') ? 'Actions that are shown' : 'Actions that are hidden'; $terms{visible} = $filter_val eq 'show' ? 1 : 0; } } $params{id} = $params{edit_author_id} = $author_id; $params{service_styles} = \@service_styles_loop; $app->listing({ type => 'profileevent', terms => \%terms, args => \%args, listing_screen => 1, code => $code, template => $plugin->load_tmpl('list_profileevent.tmpl'), params => \%params, }); } sub itemset_hide_events { my ($app) = @_; $app->validate_magic or return; my @events = $app->param('id'); for my $event_id (@events) { my $event = MT->model('profileevent')->load($event_id) or next; next if $app->user->id != $event->author_id && !$app->user->is_superuser(); $event->visible(0); $event->save; } $app->add_return_arg( hidden => 1 ); $app->call_return; } sub itemset_show_events { my ($app) = @_; $app->validate_magic or return; my @events = $app->param('id'); for my $event_id (@events) { my $event = MT->model('profileevent')->load($event_id) or next; next if $app->user->id != $event->author_id && !$app->user->is_superuser(); $event->visible(1); $event->save; } $app->add_return_arg( shown => 1 ); $app->call_return; } sub _itemset_hide_show_all_events { my ($app, $new_visible) = @_; $app->validate_magic or return; my $event_class = MT->model('profileevent'); # Really we should work directly from the selected author ID, but as an # itemset event we only got some event IDs. So use its. my ($event_id) = $app->param('id'); my $event = $event_class->load($event_id) or return $app->error($app->translate('No such event [_1]', $event_id)); my $author_id = $event->author_id; return $app->error('Not permitted to modify') if $author_id != $app->user->id && !$app->is_superuser(); my $driver = $event_class->driver; my $stmt = $driver->prepare_statement($event_class, { # TODO: include filter value when we have filters author_id => $author_id, visible => $new_visible ? 0 : 1, }); my $sql = "UPDATE " . $driver->table_for($event_class) . " SET " . $driver->dbd->db_column_name($event_class->datasource, 'visible') . " = ? " . $stmt->as_sql_where; # Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline. my $dbh = $driver->rw_handle; $dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} }) or return $app->error($dbh->errstr); return 1; } sub itemset_hide_all_events { my $app = shift; _itemset_hide_show_all_events($app, 0) or return; $app->add_return_arg( all_hidden => 1 ); $app->call_return; } sub itemset_show_all_events { my $app = shift; _itemset_hide_show_all_events($app, 1) or return; $app->add_return_arg( all_shown => 1 ); $app->call_return; } sub _build_service_data { my %info = @_; my ($networks, $streams, $author) = @info{qw( networks streams author )}; my (@service_styles_loop, @networks); my %has_profiles; if ($author) { my $other_profiles = $author->other_profiles(); $has_profiles{$_->{type}} = 1 for @$other_profiles; } my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} } keys %$networks; TYPE: for my $type (@network_keys) { my $ndata = $networks->{$type} or next TYPE; my @streams; if ($streams) { my $streamdata = $streams->{$type} || {}; @streams = sort { lc $a->{name} cmp lc $b->{name} } grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} } map { +{ stream => $_, %{ $streamdata->{$_} } } } grep { $_ ne 'plugin' } keys %$streamdata; } my $ret = { type => $type, %$ndata, label => $ndata->{name}, user_has_account => ($has_profiles{$type} ? 1 : 0), }; $ret->{streams} = \@streams if @streams; push @networks, $ret; if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') { push @service_styles_loop, { service_type => $type, service_icon => __PACKAGE__->icon_url_for_service($type, $ndata), }; } } return ( service_styles => \@service_styles_loop, networks => \@networks, ); } sub other_profiles { my( $app ) = @_; $app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id'); my $author_id = $app->param('id') or return $app->error('Author id is required'); my $user = MT->model('author')->load($author_id) or return $app->error('Author id is invalid'); return $app->error('Not permitted to view') if $app->user->id != $author_id && !$app->user->is_superuser(); my $plugin = MT->component('ActionStreams'); my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' ); my @profiles = sort { lc $a->{label} cmp lc $b->{label} } @{ $user->other_profiles || [] }; my %messages = map { $_ => $app->param($_) ? 1 : 0 } (qw( added removed updated edited )); return $app->build_page( $tmpl, { id => $user->id, edit_author_id => $user->id, profiles => \@profiles, listing_screen => 1, _build_service_data( networks => $app->registry('profile_services'), ), %messages, } ); } sub dialog_add_edit_profile { my ($app) = @_; return $app->error('Not permitted to view') if $app->user->id != $app->param('author_id') && !$app->user->is_superuser(); my $author = MT->model('author')->load($app->param('author_id')) or return $app->error('No such author [_1]', $app->param('author_id')); my %edit_profile; my $tmpl_name = 'dialog_add_profile.tmpl'; if (my $edit_type = $app->param('profile_type')) { my $ident = $app->param('profile_ident') || q{}; my ($profile) = grep { $_->{ident} eq $ident } @{ $author->other_profiles($edit_type) }; %edit_profile = ( edit_type => $edit_type, edit_type_name => $app->registry('profile_services', $edit_type, 'name'), edit_ident => $ident, edit_streams => $profile->{streams} || [], ); $tmpl_name = 'dialog_edit_profile.tmpl'; } my $plugin = MT->component('ActionStreams'); my $tmpl = $plugin->load_tmpl($tmpl_name); return $app->build_page($tmpl, { edit_author_id => $app->param('author_id'), _build_service_data( networks => $app->registry('profile_services'), streams => $app->registry('action_streams'), author => $author, ), %edit_profile, }); } sub edit_other_profile { my $app = shift; $app->validate_magic() or return; my $author_id = $app->param('author_id') or return $app->error('Author id is required'); my $user = MT->model('author')->load($author_id) or return $app->error('Author id is invalid'); return $app->error('Not permitted to edit') if $app->user->id != $author_id && !$app->user->is_superuser(); my $type = $app->param('profile_type'); my $orig_ident = $app->param('original_ident'); $user->remove_profile($type, $orig_ident); $app->forward('add_other_profile', success_msg => 'edited'); } sub add_other_profile { my $app = shift; my %param = @_; $app->validate_magic or return; my $author_id = $app->param('author_id') or return $app->error('Author id is required'); my $user = MT->model('author')->load($author_id) or return $app->error('Author id is invalid'); return $app->error('Not permitted to add') if $app->user->id != $author_id && !$app->user->is_superuser(); my( $ident, $uri, $label, $type ); if ( $type = $app->param( 'profile_type' ) ) { my $reg = $app->registry('profile_services'); my $network = $reg->{$type} or croak "Unknown network $type"; $label = $network->{name} . ' Profile'; $ident = $app->param( 'profile_id' ); $ident =~ s{ \A \s* }{}xms; $ident =~ s{ \s* \z }{}xms; # Check for full URLs. if (!$network->{ident_exact}) { my $url_pattern = $network->{url}; my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2; $pre_ident =~ s{ \A http:// }{}xms; $post_ident =~ s{ / \z }{}xms; if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) { $ident = $1; } } $uri = $network->{url}; $uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg; } else { $ident = $uri = $app->param( 'profile_uri' ); $label = $app->param( 'profile_label' ); $type = 'website'; } my $profile = { type => $type, ident => $ident, label => $label, uri => $uri, }; my %streams = map { join(q{_}, $type, $_) => 1 } grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) } keys %{ $app->registry('action_streams', $type) || {} }; $profile->{streams} = \%streams if %streams; $app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile); $user->add_profile($profile); $app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile); my $success_msg = $param{success_msg} || 'added'; return $app->redirect($app->uri( mode => 'other_profiles', args => { id => $author_id, $success_msg => 1 }, )); } sub remove_other_profile { my( $app ) = @_; $app->validate_magic or return; my %users; my $page_author_id; PROFILE: for my $profile ($app->param('id')) { my ($author_id, $type, $ident) = split /:/, $profile, 3; my $user = ($users{$author_id} ||= MT->model('author')->load($author_id)) or next PROFILE; next PROFILE if $app->user->id != $author_id && !$app->user->is_superuser(); $app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident); $user->remove_profile( $type, $ident ); $app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident); $page_author_id = $author_id; } return $app->redirect($app->uri( mode => 'other_profiles', args => { id => ($page_author_id || $app->user->id), removed => 1 }, )); } sub profile_add_external_profile { my $app = shift; my %param = @_; my $user = $app->_login_user_commenter(); return $app->error( $app->translate("Invalid request.") ) unless $user; $app->validate_magic or return; # TODO: make sure profile is an accepted type $app->param('author_id', $user->id); my $type = $app->param('profile_type') or return $app->error( $app->translate("Invalid request.") ); # The profile side interface doesn't have stream selection, so select # them all by default. # TODO: factor out the adding logic (and parameterize stream selection) to stop faking params foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) { next if $stream eq 'plugin'; $app->param(join('_', 'stream', $type, $stream), 1); } add_other_profile($app); return if $app->errstr; # forward on to community profile view return $app->redirect($app->uri( mode => 'view', args => { id => $user->id, ( $app->blog ? ( blog_id => $app->blog->id ) : () ) }, )); } sub profile_first_update_events { my ($cb, $app, $user, $profile) = @_; update_events_for_profile($user, $profile, synchronous => 1, hide_timeless => 1); } sub profile_delete_external_profile { my $app = shift;
markpasc/mt-plugin-action-streams
0d17ca331fc0517cbe662def69c00d7ed4ce9828
Make Backtype actions unique per url as the feed doesn't have guids BugzID: 87177
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml index 83a8bf3..1f9b66e 100644 --- a/plugins/ActionStreams/streams.yaml +++ b/plugins/ActionStreams/streams.yaml @@ -1,529 +1,530 @@ oneup: playing: name: Currently Playing description: The games in your collection you're currently playing class: OneupPlaying backtype: comments: name: Comments description: Comments you have made on the web fields: - queue html_form: '[_1] commented on <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://feeds.backtype.com/{{ident}}' rss: 1 + identifier: url colourlovers: colors: name: Colors description: Colors you saved fields: - queue html_form: '[_1] saved the color <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}' xpath: foreach: //color get: title: title url: url identifier: url created_on: dateCreated thumbnail: imageUrl palettes: name: Palettes description: Palettes you saved fields: - queue html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}' xpath: foreach: //palette get: title: title url: url identifier: url created_on: dateCreated thumbnail: imageUrl patterns: name: Patterns description: Patterns you saved fields: - queue html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}' xpath: foreach: //pattern get: title: title url: url identifier: url created_on: dateCreated thumbnail: imageUrl favpalettes: name: Favorite Palettes description: Palettes you saved as favorites fields: - queue html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette' html_params: - url - title url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites' rss: 1 corkd: reviews: name: Reviews description: Your wine reviews fields: - review html_form: '[_1] reviewed <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.corkd.com/feed/journal/{{ident}}' rss: 1 cellar: name: Cellar description: Wines you own fields: - wine html_form: '[_1] owns <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.corkd.com/feed/cellar/{{ident}}' rss: 1 list: name: Shopping List description: Wines you want to buy fields: - wine html_form: '[_1] wants <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}' rss: 1 delicious: links: name: Links description: Your public links fields: - note html_form: '[_1] saved the link <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://feeds.delicious.com/rss/{{ident}}' identifier: url xpath: foreach: //item get: created_on: dc:date title: title url: link note: description digg: links: name: Dugg description: Links you dugg html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://digg.com/users/{{ident}}/history/diggs.rss' identifier: url fetch: default_useragent: 1 xpath: foreach: //item get: created_on: pubDate title: title url: link submitted: name: Submissions description: Links you submitted html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>' html_params: - url - title url: http://digg.com/users/{{ident}}/history/submissions.rss identifier: url fetch: default_useragent: 1 xpath: foreach: //item get: created_on: pubDate title: title url: link ffffound: favorites: name: Found description: Photos you found html_form: '[_1] ffffound <a href="[_2]">[_3]</a>' html_params: - url - title url: http://ffffound.com/home/{{ident}}/found/feed rss: 1 flickr: favorites: name: Favorites description: Photos you marked as favorites fields: - by html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo' html_params: - url - title url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10' atom: thumbnail: content by: author/name photos: name: Photos description: Photos you posted html_form: '[_1] posted <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10' atom: thumbnail: content friendfeed: likes: name: Likes description: Things from your friends that you "like" html_form: '[_1] likes <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://friendfeed.com/{{ident}}/likes?format=atom' atom: url: link/@href gametap: scores: name: Leaderboard scores description: Your high scores in games with leaderboards fields: - score html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>' html_params: - score - url - title url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}} identifier: title,score scraper: foreach: 'div.buddy-leaderboards div.tr' get: url: - 'div.name a' - '@href' title: - 'div.name strong' - TEXT score: - 'div.name div' - TEXT gblogs: posts: name: Posts description: Blog posts about your search term html_form: 'Google Blog Search result: <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://blogsearch.google.com/blogsearch_feeds?q=%22{{ident}}%22&ie=utf-8&num=10&output=atom&scoring=d' identifier: url atom: 1 gnews: stories: name: Stories description: News Stories matching your search html_form: 'Google News search result: <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://news.google.com/news?num=100&q=%22{{ident}}%22&output=atom' identifier: url atom: 1 goodreads: toread: name: To read description: Books on your "to-read" shelf fields: - by html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read' html_params: - url - title - by url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read' identifier: url xpath: foreach: //item get: title: title url: link created_on: pubDate modified_on: pubDate by: author_name reading: name: Reading description: Books on your "currently-reading" shelf fields: - by html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>' html_params: - url - title - by url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading' identifier: url xpath: foreach: //item get: title: title url: link created_on: pubDate modified_on: pubDate by: author_name read: name: Read description: Books on your "read" shelf fields: - by html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>' html_params: - url - title - by url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read' identifier: url xpath: foreach: //item get: title: title url: link created_on: pubDate modified_on: pubDate by: author_name googlereader: links: name: Shared description: Your shared items html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>' html_params: - url - title - source_url - source_title class: GoogleReader iconbuffet: icons: name: Deliveries description: Icon sets you were delivered html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.iconbuffet.com/people/{{ident}};received_packages' identifier: url scraper: foreach: 'div#icons div.preview-sm' get: title: - a span - TEXT url: - a - '@href' identica: statuses: name: Notices description: Notices you posted html_form: '[_1] <a href="[_2]">said</a>, &ldquo;[_3]&rdquo;' html_params: - url - title url: 'http://identi.ca/{{ident}}/rss' rss: created_on: dc:date class: Identica iminta: links: name: Intas description: Links you saved html_form: '[_1] is inta <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11' rss: 1 istockphoto: photos: name: Photos description: Photos you posted that were approved html_form: '[_1] posted <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}' identifier: url atom: thumbnail: content/div/a/img/@src iusethis: events: name: Recent events description: Events from your recent events feed html_form: '[_1] <a href="[_2]">[_3]</a>' html_params: - url - title rss: 1 url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0' osxapps: name: Apps you use description: The applications you saved as ones you use fields: - favorite html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]' html_params: - url - title - favorite url: 'http://osx.iusethis.com/user/{{ident}}' iwatchthis: favorites: name: Favorites description: Videos you saved as watched html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video' html_params: - url - title url: 'http://iwatchthis.com/rss/{{ident}}' rss: 1 jaiku: jaikus: name: Jaikus description: Jaikus you posted html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"' html_params: - url - title url: 'http://{{ident}}.jaiku.com/feed/atom' atom: 1 kongregate: favorites: name: Favorites description: Games you saved as favorites html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game' html_params: - url - title url: 'http://www.kongregate.com/accounts/{{ident}}' identifier: url scraper: foreach: #favorites dl get: url: - dd a - '@href' title: - dd a - TEXT thumbnail: - dt img - '@src' achievements: name: Achievements description: Achievements you won fields: - game_title html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>' html_params: - title - url - game_title url: 'http://www.kongregate.com/accounts/{{ident}}' identifier: url,title scraper: foreach: #achievements .badge_details get: url: - dt.badge_img a - '@href' thumbnail: - dt.badge_img img - '@style' title: - dd.badge_name - TEXT game_title: - a.badge_game - TEXT lastfm: tracks: name: Tracks description: Songs you recently listened to (High spam potential!) html_form: '[_1] heard <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss' rss: 1 lovedtracks: name: Loved Tracks description: Songs you marked as "loved" fields: - artist html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]' html_params: - url - title - artist url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}' identifier: url rss: artist: description journalentries: name: Journal Entries description: Your recent journal entries html_form: '[_1] posted <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss' rss: 1 events: name: Events description: The events you said you'll be attending html_form: '[_1] is attending <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss' rss: 1 livejournal: posts: name: Posts description: Your public posts to your journal html_form: '[_1] posted <a href="[_2]">[_3]</a>' html_params: - url - title url: 'http://users.livejournal.com/{{ident}}/data/atom'
markpasc/mt-plugin-action-streams
e28c6e416236da07f6fae981f3081a9c392e5a7a
Reverting the change at r3123. Page Archive is a entry archive. BugId:82643
diff --git a/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl b/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl index f18301a..2cee720 100644 --- a/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl +++ b/plugins/ActionStreams/tmpl/dialog_add_profile.tmpl @@ -1,206 +1,210 @@ <mt:setvarblock name="page_title"><__trans phrase="Add Profile"></mt:setvarblock> <mt:setvarblock name="html_head" append="1"> <link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" /> <mt:loop name="service_styles"> <mt:if name="__first__"> <style type="text/css"> <!-- </mt:if> .service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); } <mt:if name="__last__"> // --> </style> </mt:if> </mt:loop> <script type="text/javascript"> <!-- function validate(f) { if (!f.profile_id.value) { alert('<__trans phrase="Your user name or ID is required." escape="singlequotes">'); return false; } return true; } // --> </script> </mt:setvarblock> <mt:include name="dialog/header.tmpl"> <script type="text/javascript" src="<mt:var name="static_uri">js/tc/client.js"></script> <script type="text/javascript" src="<mt:var name="static_uri">js/dialog.js"></script> <div class="modal_width" id="add-profile"> <p>Add a profile on a social networking or instant messaging service.</p> <form id="add-network" method="post" action="<mt:var name="script_url">" onsubmit="return validate(this)" target="_top"> <input type="hidden" name="__mode" value="add_other_profile" /> <input type="hidden" name="author_id" value="<mt:var name="edit_author_id">" /> <input type="hidden" name="magic_token" value="<mt:var name="magic_token">" /> <mtapp:setting id="profile_type" label="<__trans phrase="Service">" hint="<__trans phrase="Select a service where you already have an account.">" show_hint="1" content_class="field-content-text"> <select name="profile_type" id="profile_type"> <mt:loop name="networks"> <mt:if name="user_has_account"> <mt:if name="can_many"> <option value="<mt:var name="type" escape="html">"><mt:var name="label" escape="html"></option> </mt:if> <mt:else> <option value="<mt:var name="type" escape="html">"><mt:var name="label" escape="html"></option> </mt:if> </mt:loop> </select> </mtapp:setting> <script type="text/javascript"> var last_network; var networks = { <mt:loop name="networks"> '<mt:var name="type" escape="js">': { <mt:if name="ident_example"> example: '<mt:var name="ident_example" escape="js">', </mt:if> <mt:if name="ident_prefix"> prefix: '<mt:var name="ident_prefix" escape="js">', </mt:if> <mt:if name="ident_suffix"> suffix: '<mt:var name="ident_suffix" escape="js">', </mt:if> label: '<mt:var name="ident_label" escape="js">' }<mt:unless var="__last__">,</mt:unless> </mt:loop> }; function update_ident_field () { var v = getByID('profile_type'); var data = new Object(); data.label = "Username"; data.example = "melody"; data.prefix = ""; data.suffix = ""; var fields = ['label', 'example', 'prefix', 'suffix']; for(var i = 0; i < 4; i++) { var l = fields[i]; var datum = data[l]; if (networks[v.value] && networks[v.value][l]) { datum = networks[v.value][l]; } var f = getByID('profile_id-' + l); f.innerHTML = datum; } if (last_network) { hide('help-' + last_network, document); hide('streams-' + last_network, document); var streams = getByID('streams-' + last_network); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; stream_boxes[i].checked = false; } } show('help-' + v.value, document); show('streams-' + v.value, document); var streams = getByID('streams-' + v.value); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; stream_boxes[i].checked = true; } var icon = getByID('profile-id-service-icon'); if (last_network) { DOM.removeClassName(icon, 'service-' + last_network); } DOM.addClassName(icon, 'service-' + v.value); last_network = v.value; } function add_in_update (e) { var v = getByID('profile_type'); DOM.addEventListener(v, 'change', update_ident_field); update_ident_field(); } TC.attachLoadEvent(add_in_update); </script> <mtapp:setting id="profile_id" label="<__trans phrase="Username">" hint="<__trans phrase="Enter your account on the selected service."><br /><__trans phrase="For example:"> <strong id='profile_id-example'>melody</strong>" show_hint="1" content_class="field-content-text"> <span id="profile-id-service-icon" class="service-icon"> <span id="profile_id-prefix"></span> <input type="text" name="profile_id" size="30" value="" /> <span id="profile_id-suffix"></span> </span> </mtapp:setting> <div id="help-facebook" class="hidden"> <div class="hint">You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.</div> </div> <div id="help-netflix" class="hidden"> <mtapp:statusmsg class="info">To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.</mtapp:statusmsg> </div> + <div id="help-flickr" class="hidden"> + <div class="hint">Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.</div> + </div> + <h3>Action Streams</h3> <p>Select the action streams to collect from the selected service.</p> <mt:loop name="networks"> <div id="streams-<mt:var name="type" escape="html">" class="hidden"> <mt:if name="streams"> <mt:loop name="streams"> <mt:setvarblock name="stream_id">stream_<mt:var name="type" escape="html">_<mt:var name="stream" escape="html"></mt:setvarblock> <mtapp:setting id="<mt:var name="stream_id">" label="<mt:var name="name" escape="html">"> <label><input type="checkbox" id="<mt:var name="stream_id">" name="<mt:var name="stream_id">" value="1" /> <mt:var name="description" escape="html"></label> </mtapp:setting> </mt:loop> <mt:else> <mtapp:statusmsg class="info zero-state">No streams are available for this service.</mtapp:statusmsg> </mt:if> </div> </mt:loop> <mt:setvarblock name="action_buttons"> <button type="submit" accesskey="s" title="<__trans phrase="Add Service (s)">" class="primary-button" ><__trans phrase="Add Service"></button> <button onclick="closeDialog(); return false" type="submit" accesskey="x" title="<__trans phrase="Cancel (x)">" class="cancel" ><__trans phrase="Cancel"></button> </mt:setvarblock> <mt:include name="include/actions_bar.tmpl" bar_position="normal" hide_pager="1" settings_bar="1"> </form> </div> <mt:include name="dialog/footer.tmpl"> diff --git a/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl b/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl index 64640d5..0403a73 100644 --- a/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl +++ b/plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl @@ -1,203 +1,207 @@ <mt:setvarblock name="page_title"><__trans phrase="Edit Profile"></mt:setvarblock> <mt:setvarblock name="html_head" append="1"> <link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" /> <mt:loop name="service_styles"> <mt:if name="__first__"> <style type="text/css"> <!-- </mt:if> .service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); } <mt:if name="__last__"> // --> </style> </mt:if> </mt:loop> <script type="text/javascript"> <!-- function validate(f) { if (!f.profile_id.value) { alert('<__trans phrase="Your user name or ID is required." escape="singlequotes">'); return false; } return true; } // --> </script> </mt:setvarblock> <mt:include name="dialog/header.tmpl"> <script type="text/javascript" src="<mt:var name="static_uri">js/tc/client.js"></script> <script type="text/javascript" src="<mt:var name="static_uri">js/dialog.js"></script> <div class="modal_width" id="edit-profile"> <p>Edit a profile on a social networking or instant messaging service.</p> <form id="edit-network" method="post" action="<mt:var name="script_url">" onsubmit="return validate(this)" target="_top"> <input type="hidden" name="__mode" value="edit_other_profile" /> <input type="hidden" name="author_id" value="<mt:var name="edit_author_id">" /> <input type="hidden" name="original_ident" value="<mt:var name="edit_ident" escape="html">" /> <input type="hidden" name="magic_token" value="<mt:var name="magic_token">" /> <mtapp:setting id="profile_type" label="<__trans phrase="Service">" content_class="field-content-text"> <strong><mt:var name="edit_type_name" escape="html"></strong> <input type="hidden" name="profile_type" id="profile_type" value="<mt:var name="edit_type" escape="html">" /> </mtapp:setting> <script type="text/javascript"> var last_network; var networks = { <mt:loop name="networks"> '<mt:var name="type" escape="js">': { <mt:if name="ident_example"> example: '<mt:var name="ident_example" escape="js">', </mt:if> <mt:if name="ident_prefix"> prefix: '<mt:var name="ident_prefix" escape="js">', </mt:if> <mt:if name="ident_suffix"> suffix: '<mt:var name="ident_suffix" escape="js">', </mt:if> label: '<mt:var name="ident_label" escape="js">' }<mt:unless var="__last__">,</mt:unless> </mt:loop> }; var edit_streams = { <mt:loop name="edit_streams"> 'stream_<mt:var name="__key__" escape="js">': '<mt:var name="__value__" escape="js">'<mt:unless name="__last__">,</mt:unless> </mt:loop> }; function update_ident_field () { var v = getByID('profile_type'); var data = new Object(); data.label = "Username"; data.example = "melody"; data.prefix = ""; data.suffix = ""; var fields = ['label', 'example', 'prefix', 'suffix']; for(var i = 0; i < 4; i++) { var l = fields[i]; var datum = data[l]; if (networks[v.value] && networks[v.value][l]) { datum = networks[v.value][l]; } var f = getByID('profile_id-' + l); f.innerHTML = datum; } if (last_network) { hide('help-' + last_network, document); hide('streams-' + last_network, document); var streams = getByID('streams-' + last_network); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; stream_boxes[i].checked = false; } } show('help-' + v.value, document); show('streams-' + v.value, document); var streams = getByID('streams-' + v.value); var stream_boxes = streams.getElementsByTagName('input'); for (var i = 0; i < stream_boxes.length; i++) { if (stream_boxes[i].type != 'checkbox') continue; if (edit_streams[ stream_boxes[i].name ]) stream_boxes[i].checked = true; } var icon = getByID('profile-id-service-icon'); if (last_network) { DOM.removeClassName(icon, 'service-' + last_network); } DOM.addClassName(icon, 'service-' + v.value); last_network = v.value; } function add_in_update (e) { var v = getByID('profile_type'); DOM.addEventListener(v, 'change', update_ident_field); update_ident_field(); } TC.attachLoadEvent(add_in_update); </script> <mtapp:setting id="profile_id" label="<__trans phrase="Username">" hint="<__trans phrase="Enter your account on the selected service."><br /><__trans phrase="For example:"> <strong id='profile_id-example'>melody</strong>" show_hint="1" content_class="field-content-text"> <span id="profile-id-service-icon" class="service-icon"> <span id="profile_id-prefix"></span> <input type="text" name="profile_id" size="30" value="<mt:var name="edit_ident" escape="html">" /> <span id="profile_id-suffix"></span> </span> </mtapp:setting> <div id="help-facebook" class="hidden"> <div class="hint">You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.</div> </div> <div id="help-netflix" class="hidden"> <mtapp:statusmsg class="info">To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.</mtapp:statusmsg> </div> + <div id="help-flickr" class="hidden"> + <div class="hint">Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.</div> + </div> + <h3>Action Streams</h3> <p>Select the action streams to collect from the selected service.</p> <mt:loop name="networks"> <div id="streams-<mt:var name="type" escape="html">" class="hidden"> <mt:if name="streams"> <mt:loop name="streams"> <mt:setvarblock name="stream_id">stream_<mt:var name="type" escape="html">_<mt:var name="stream" escape="html"></mt:setvarblock> <mtapp:setting id="<mt:var name="stream_id">" label="<mt:var name="name" escape="html">"> <label><input type="checkbox" id="<mt:var name="stream_id">" name="<mt:var name="stream_id">" value="1" /> <mt:var name="description" escape="html"></label> </mtapp:setting> </mt:loop> <mt:else> <mtapp:statusmsg class="info zero-state">No streams are available for this service.</mtapp:statusmsg> </mt:if> </div> </mt:loop> <mt:setvarblock name="action_buttons"> <button type="submit" accesskey="s" title="<__trans phrase="Save Changes (s)">" class="primary-button" ><__trans phrase="Save Changes"></button> <button onclick="closeDialog(); return false" type="submit" accesskey="x" title="<__trans phrase="Cancel (x)">" class="cancel" ><__trans phrase="Cancel"></button> </mt:setvarblock> <mt:include name="include/actions_bar.tmpl" bar_position="normal" hide_pager="1" settings_bar="1"> </form> </div> <mt:include name="dialog/footer.tmpl">
PeteMo/sethostname
4368bba412e60c658292d25b9a8f639ef6914daf
End if statement correctly
diff --git a/sethostname b/sethostname index 5e02143..b558e39 100644 --- a/sethostname +++ b/sethostname @@ -1,47 +1,48 @@ #!/bin/bash #-------------------------------------------------------------------- # Set a computer's hostname. OS X specific. # # Usage: sethostname <interface> </path/to/hostnames/file> # # The hostnames file must be a list of mac addresses and hostname # pairs, one per line, separated by whitespace. Run the script on # the computer whose hostname you want to change. The hostname # cannot contain spaces. # # Configured for Leopard; change path to networksetup Tiger or older. #-------------------------------------------------------------------- usage() { echo "Usage: # $0 <interface> </path/to/hostnames/file>" >&2 } # Check usage. if [ $(whoami) != 'root' ]; then echo "$(basename $0) must be run as root" exit 1 fi if [ $# != 2 ]; then usage exit 1 fi if [ -f $2 ]; then hostfile=$2 else echo "$2 is not a regular file" exit 1 fi # Find the hostname and apply it. iface=$1 mac=$(ifconfig $iface | awk '/ether/ {print $2}') hostname=$(awk "/$mac/ {print \$2}" $hostfile) if [[ $hostname == "" ]]; then echo "Problem getting hostname, check $hostfile" >&2 else scutil --set HostName $hostname /usr/sbin/networksetup -setcomputername $hostname +fi
PeteMo/sethostname
2e1f9dc87c9fbcdf2d8fb52d7c5e1b2253d3642d
Fix spelling error
diff --git a/sethostname b/sethostname index e7c6565..5e02143 100644 --- a/sethostname +++ b/sethostname @@ -1,47 +1,47 @@ #!/bin/bash #-------------------------------------------------------------------- # Set a computer's hostname. OS X specific. # # Usage: sethostname <interface> </path/to/hostnames/file> # # The hostnames file must be a list of mac addresses and hostname # pairs, one per line, separated by whitespace. Run the script on # the computer whose hostname you want to change. The hostname # cannot contain spaces. # -# Configured for Leopard; chang path to networksetup Tiger or older. +# Configured for Leopard; change path to networksetup Tiger or older. #-------------------------------------------------------------------- usage() { echo "Usage: # $0 <interface> </path/to/hostnames/file>" >&2 } # Check usage. if [ $(whoami) != 'root' ]; then echo "$(basename $0) must be run as root" exit 1 fi if [ $# != 2 ]; then usage exit 1 fi if [ -f $2 ]; then hostfile=$2 else echo "$2 is not a regular file" exit 1 fi # Find the hostname and apply it. iface=$1 mac=$(ifconfig $iface | awk '/ether/ {print $2}') hostname=$(awk "/$mac/ {print \$2}" $hostfile) if [[ $hostname == "" ]]; then echo "Problem getting hostname, check $hostfile" >&2 else scutil --set HostName $hostname /usr/sbin/networksetup -setcomputername $hostname
PeteMo/sethostname
96de4b8bc984915011e3620477e22cb81c8d393d
Initial import
diff --git a/sethostname b/sethostname new file mode 100644 index 0000000..e7c6565 --- /dev/null +++ b/sethostname @@ -0,0 +1,47 @@ +#!/bin/bash + +#-------------------------------------------------------------------- +# Set a computer's hostname. OS X specific. +# +# Usage: sethostname <interface> </path/to/hostnames/file> +# +# The hostnames file must be a list of mac addresses and hostname +# pairs, one per line, separated by whitespace. Run the script on +# the computer whose hostname you want to change. The hostname +# cannot contain spaces. +# +# Configured for Leopard; chang path to networksetup Tiger or older. +#-------------------------------------------------------------------- + +usage() { + echo "Usage: # $0 <interface> </path/to/hostnames/file>" >&2 +} + +# Check usage. +if [ $(whoami) != 'root' ]; then + echo "$(basename $0) must be run as root" + exit 1 +fi + +if [ $# != 2 ]; then + usage + exit 1 +fi + +if [ -f $2 ]; then + hostfile=$2 +else + echo "$2 is not a regular file" + exit 1 +fi + +# Find the hostname and apply it. +iface=$1 +mac=$(ifconfig $iface | awk '/ether/ {print $2}') +hostname=$(awk "/$mac/ {print \$2}" $hostfile) + +if [[ $hostname == "" ]]; then + echo "Problem getting hostname, check $hostfile" >&2 +else + scutil --set HostName $hostname + /usr/sbin/networksetup -setcomputername $hostname
pkrumins/node-jpeg
15a12d6286e7e1d32990f736d73a0c31dd540981
v2.0.0 now
diff --git a/package.json b/package.json index 182c2b3..601e0d7 100644 --- a/package.json +++ b/package.json @@ -1,35 +1,35 @@ { "name": "jpeg", - "version": "1.0.3", + "version": "2.0.0", "main": "build/Release/jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "author": { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" }, "license": "MIT", "repository": { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" }, "directories": { "examples": "examples", "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-gyp configure build" } }
pkrumins/node-jpeg
becc5ee99fa3bb2a94aeb6b267c4c16046ae745a
add module declare
diff --git a/src/module.cpp b/src/module.cpp index 593142d..539139c 100644 --- a/src/module.cpp +++ b/src/module.cpp @@ -1,17 +1,18 @@ #include <node.h> #include "jpeg.h" #include "fixed_jpeg_stack.h" #include "dynamic_jpeg_stack.h" using namespace v8; extern "C" void init(Handle<Object> target) { HandleScope scope; Jpeg::Initialize(target); FixedJpegStack::Initialize(target); DynamicJpegStack::Initialize(target); } +NODE_MODULE(jpeg, init)
pkrumins/node-jpeg
0c277810cb4758cbd88e58d7249c8d963582c395
Revert "v8::"
diff --git a/src/module.cpp b/src/module.cpp index 8039e8d..593142d 100644 --- a/src/module.cpp +++ b/src/module.cpp @@ -1,17 +1,17 @@ #include <node.h> #include "jpeg.h" #include "fixed_jpeg_stack.h" #include "dynamic_jpeg_stack.h" using namespace v8; extern "C" void -init(v8::Handle<v8::Object> target) +init(Handle<Object> target) { - v8::HandleScope scope; + HandleScope scope; Jpeg::Initialize(target); FixedJpegStack::Initialize(target); DynamicJpegStack::Initialize(target); }
pkrumins/node-jpeg
77814182b453ba1e2b23b9e899d219f1f01b24d6
changed config on win
diff --git a/binding.gyp b/binding.gyp index 160f8f6..49570ce 100644 --- a/binding.gyp +++ b/binding.gyp @@ -1,45 +1,44 @@ { "targets": [ { "target_name": "jpeg", "sources": [ "src/common.cpp", "src/jpeg_encoder.cpp", "src/jpeg.cpp", "src/fixed_jpeg_stack.cpp", "src/dynamic_jpeg_stack.cpp", "src/module.cpp", ], "conditions" : [ [ 'OS=="linux"', { "libraries" : [ '-ljpeg' ], 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ] } ], [ 'OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' }, "libraries" : [ '-ljpeg' ] } ], [ 'OS=="win"', { "include_dirs" : [ "gyp/include" ], "libraries" : [ - '<(module_root_dir)/gyp/lib/libpng.lib', - '<(module_root_dir)/gyp/lib/zlib.lib' + '<(module_root_dir)/gyp/lib/libjpeg.lib' ] } ] ] } ] }
pkrumins/node-jpeg
c7f822d9fd84d9261423a28aa3aef5dbff1991d4
node-waf --> node-gyp compatible for node 0.10.x
diff --git a/binding.gyp b/binding.gyp new file mode 100644 index 0000000..160f8f6 --- /dev/null +++ b/binding.gyp @@ -0,0 +1,45 @@ +{ + "targets": [ + { + "target_name": "jpeg", + "sources": [ + "src/common.cpp", + "src/jpeg_encoder.cpp", + "src/jpeg.cpp", + "src/fixed_jpeg_stack.cpp", + "src/dynamic_jpeg_stack.cpp", + "src/module.cpp", + ], + "conditions" : [ + [ + 'OS=="linux"', { + "libraries" : [ + '-ljpeg' + ], + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions' ] + } + ], + [ + 'OS=="mac"', { + 'xcode_settings': { + 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' + }, + "libraries" : [ + '-ljpeg' + ] + } + ], + [ + 'OS=="win"', { + "include_dirs" : [ "gyp/include" ], + "libraries" : [ + '<(module_root_dir)/gyp/lib/libpng.lib', + '<(module_root_dir)/gyp/lib/zlib.lib' + ] + } + ] + ] + } + ] +} diff --git a/package.json b/package.json index ce43a89..182c2b3 100644 --- a/package.json +++ b/package.json @@ -1,35 +1,35 @@ { "name": "jpeg", "version": "1.0.3", "main": "build/Release/jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "author": { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" }, "license": "MIT", "repository": { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" }, "directories": { "examples": "examples", "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { - "install": "node-waf configure build" + "install": "node-gyp configure build" } } diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index 77058a6..3bc4eaa 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,478 +1,477 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Local<Object> data_buf = args[0]->ToObject(); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)Buffer::Data(data_buf), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Local<Object> data_buf = args[0]->ToObject(); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)Buffer::Data(data_buf), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } void -DynamicJpegStack::EIO_JpegEncode(eio_req *req) +DynamicJpegStack::UV_JpegEncode(uv_work_t *req) { encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; try { Rect &dyn_rect = jpeg->dyn_rect; JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { - enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); + enc_req->error = strdup("malloc in DynamicJpegStack::UV_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } -int -DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) +void +DynamicJpegStack::UV_JpegEncodeAfter(uv_work_t *req) { HandleScope scope; - ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; + delete req; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; Handle<Value> argv[3]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = Undefined(); argv[2] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = jpeg->Dimensions(); argv[2] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); jpeg->Unref(); free(enc_req); - - return 0; } Handle<Value> DynamicJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; - eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); + uv_work_t* req = new uv_work_t; + req->data = enc_req; + uv_queue_work(uv_default_loop(), req, UV_JpegEncode, (uv_after_work_cb)UV_JpegEncodeAfter); - ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h index dae3672..f2069ef 100644 --- a/src/dynamic_jpeg_stack.h +++ b/src/dynamic_jpeg_stack.h @@ -1,49 +1,49 @@ #ifndef DYNAMIC_JPEG_H #define DYNAMIC_JPEG_H #include <node.h> #include <node_buffer.h> #include <vector> #include <utility> #include "common.h" #include "jpeg_encoder.h" class DynamicJpegStack : public node::ObjectWrap { int quality; buffer_type buf_type; unsigned char *data; int bg_width, bg_height; // background width and height after setBackground Rect dyn_rect; // rect of dynamic push area (updated after each push) void update_optimal_dimension(int x, int y, int w, int h); - static void EIO_JpegEncode(eio_req *req); - static int EIO_JpegEncodeAfter(eio_req *req); + static void UV_JpegEncode(uv_work_t *req); + static void UV_JpegEncodeAfter(uv_work_t *req); public: DynamicJpegStack(buffer_type bbuf_type); ~DynamicJpegStack(); v8::Handle<v8::Value> JpegEncodeSync(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetBackground(unsigned char *data_buf, int w, int h); void SetQuality(int q); v8::Handle<v8::Value> Dimensions(); void Reset(); static void Initialize(v8::Handle<v8::Object> target); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); static v8::Handle<v8::Value> Reset(const v8::Arguments &args); }; #endif diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index ed75fe1..4815344 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,343 +1,341 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Local<Object> data_buf = args[0]->ToObject(); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)Buffer::Data(data_buf), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } void -FixedJpegStack::EIO_JpegEncode(eio_req *req) +FixedJpegStack::UV_JpegEncode(uv_work_t *req) { encode_request *enc_req = (encode_request *)req->data; FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; try { JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { - enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); + enc_req->error = strdup("malloc in FixedJpegStack::UV_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } -int -FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) +void +FixedJpegStack::UV_JpegEncodeAfter(uv_work_t *req) { HandleScope scope; - ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; + delete req; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); free(enc_req); - - return 0; } Handle<Value> FixedJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; - eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); - - ev_ref(EV_DEFAULT_UC); + uv_work_t* req = new uv_work_t; + req->data = enc_req; + uv_queue_work(uv_default_loop(), req, UV_JpegEncode, (uv_after_work_cb)UV_JpegEncodeAfter); jpeg->Ref(); return Undefined(); } diff --git a/src/fixed_jpeg_stack.h b/src/fixed_jpeg_stack.h index 849505a..3aaa43b 100644 --- a/src/fixed_jpeg_stack.h +++ b/src/fixed_jpeg_stack.h @@ -1,34 +1,34 @@ #ifndef STACKED_JPEG_H #define STACKED_JPEG_H #include <node.h> #include <node_buffer.h> #include "common.h" #include "jpeg_encoder.h" class FixedJpegStack : public node::ObjectWrap { int width, height, quality; buffer_type buf_type; unsigned char *data; - static void EIO_JpegEncode(eio_req *req); - static int EIO_JpegEncodeAfter(eio_req *req); + static void UV_JpegEncode(uv_work_t *req); + static void UV_JpegEncodeAfter(uv_work_t *req); public: static void Initialize(v8::Handle<v8::Object> target); FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncodeSync(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif diff --git a/src/jpeg.cpp b/src/jpeg.cpp index cf0a0eb..a2ca062 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,262 +1,261 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "setSmoothing", SetSmoothing); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder(ddata, wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } void Jpeg::SetSmoothing(int s) { jpeg_encoder.set_smoothing(s); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Local<Object> buffer = args[0]->ToObject(); Jpeg *jpeg = new Jpeg((unsigned char*) Buffer::Data(buffer), w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } v8::Handle<v8::Value> Jpeg::SetSmoothing(const v8::Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int s = args[0]->Int32Value(); if (s < 0) return VException("Smoothing must be greater or equal to 0."); if (s > 100) return VException("Smoothing must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetSmoothing(s); return Undefined(); } void -Jpeg::EIO_JpegEncode(eio_req *req) +Jpeg::UV_JpegEncode(uv_work_t *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { - enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); + enc_req->error = strdup("malloc in Jpeg::UV_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } -int -Jpeg::EIO_JpegEncodeAfter(eio_req *req) +void +Jpeg::UV_JpegEncodeAfter(uv_work_t *req) { HandleScope scope; - ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; + delete req; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); - - return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; - eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); + uv_work_t* req = new uv_work_t; + req->data = enc_req; + uv_queue_work(uv_default_loop(), req, UV_JpegEncode, (uv_after_work_cb)UV_JpegEncodeAfter); - ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/jpeg.h b/src/jpeg.h index c60b809..acee92b 100644 --- a/src/jpeg.h +++ b/src/jpeg.h @@ -1,29 +1,29 @@ #ifndef JPEG_H #define JPEG_H #include <node.h> #include <node_buffer.h> #include "jpeg_encoder.h" class Jpeg : public node::ObjectWrap { JpegEncoder jpeg_encoder; - static void EIO_JpegEncode(eio_req *req); - static int EIO_JpegEncodeAfter(eio_req *req); + static void UV_JpegEncode(uv_work_t *req); + static void UV_JpegEncodeAfter(uv_work_t *req); public: static void Initialize(v8::Handle<v8::Object> target); Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncodeSync(); void SetQuality(int q); void SetSmoothing(int s); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); static v8::Handle<v8::Value> SetSmoothing(const v8::Arguments &args); }; #endif
pkrumins/node-jpeg
af1874056013dde2770db8052388a51286687660
1.0.3 now
diff --git a/package.json b/package.json index 18e2b8e..ce43a89 100644 --- a/package.json +++ b/package.json @@ -1,35 +1,35 @@ { "name": "jpeg", - "version": "1.0.2", + "version": "1.0.3", "main": "build/Release/jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "author": { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" }, "license": "MIT", "repository": { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" }, "directories": { "examples": "examples", "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-waf configure build" } }
pkrumins/node-jpeg
cc9c4a4fe0b540c9279dedcf25f80f3043ddd551
Revert "show encode timings"
diff --git a/src/jpeg_encoder.cpp b/src/jpeg_encoder.cpp index 0cf6d03..0ff82de 100644 --- a/src/jpeg_encoder.cpp +++ b/src/jpeg_encoder.cpp @@ -1,218 +1,210 @@ #include "jpeg_encoder.h" -#include "time.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), smoothing(0), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } #if JPEG_LIB_VERSION < 80 // copied over from latest libjpeg #define OUTPUT_BUF_SIZE 4096 typedef struct { struct jpeg_destination_mgr pub; /* public fields */ unsigned char ** outbuffer; /* target buffer */ unsigned long * outsize; unsigned char * newbuffer; /* newly allocated buffer */ JOCTET * buffer; /* start of buffer */ size_t bufsize; } my_mem_destination_mgr; typedef my_mem_destination_mgr * my_mem_dest_ptr; void init_mem_destination (j_compress_ptr cinfo) { /* no work necessary here */ } boolean empty_mem_output_buffer (j_compress_ptr cinfo) { size_t nextsize; JOCTET * nextbuffer; my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; /* Try to allocate new buffer with double size */ nextsize = dest->bufsize * 2; nextbuffer = (JOCTET *)malloc(nextsize); if (nextbuffer == NULL) throw "malloc failed in empty_mem_output_buffer"; memcpy(nextbuffer, dest->buffer, dest->bufsize); if (dest->newbuffer != NULL) free(dest->newbuffer); dest->newbuffer = nextbuffer; dest->pub.next_output_byte = nextbuffer + dest->bufsize; dest->pub.free_in_buffer = dest->bufsize; dest->buffer = nextbuffer; dest->bufsize = nextsize; return TRUE; } void term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; } void jpeg_mem_dest (j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize) { my_mem_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_mem_dest. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_mem_destination_mgr)); } dest = (my_mem_dest_ptr) cinfo->dest; dest->pub.init_destination = init_mem_destination; dest->pub.empty_output_buffer = empty_mem_output_buffer; dest->pub.term_destination = term_mem_destination; dest->outbuffer = outbuffer; dest->outsize = outsize; dest->newbuffer = NULL; if (*outbuffer == NULL || *outsize == 0) { /* Allocate initial buffer */ dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE); if (dest->newbuffer == NULL) throw "out of memory in jpeg_mem_dest (copied implementation)"; *outsize = OUTPUT_BUF_SIZE; } dest->pub.next_output_byte = dest->buffer = *outbuffer; dest->pub.free_in_buffer = dest->bufsize = *outsize; } #endif void JpegEncoder::encode() { - - - clock_t t = clock(); - struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); cinfo.smoothing_factor = smoothing; jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; switch (buf_type) { case BUF_RGBA: rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; break; case BUF_BGRA: rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; break; case BUF_BGR: rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; break; case BUF_RGB: rgb_data = data; break; default: throw "Unexpected buf_type in JpegEncoder::encode"; } JSAMPROW row_pointer; int start = 0; if (!offset.isNull()) { start = offset.y*width*3 + offset.x*3; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_BGR || buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); - - t = clock() - t; - printf ("encode( took %d clicks (%f ms).\n",(int)t,((float)(t*1000))/CLOCKS_PER_SEC); } void JpegEncoder::set_quality(int q) { quality = q; } void JpegEncoder::set_smoothing(int ssmoothing) { smoothing = ssmoothing; } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; }
pkrumins/node-jpeg
57697029aa659dba943fbb1df5f7652a5a0171a6
show encode timings
diff --git a/src/jpeg_encoder.cpp b/src/jpeg_encoder.cpp index 0ff82de..0cf6d03 100644 --- a/src/jpeg_encoder.cpp +++ b/src/jpeg_encoder.cpp @@ -1,210 +1,218 @@ #include "jpeg_encoder.h" +#include "time.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), smoothing(0), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } #if JPEG_LIB_VERSION < 80 // copied over from latest libjpeg #define OUTPUT_BUF_SIZE 4096 typedef struct { struct jpeg_destination_mgr pub; /* public fields */ unsigned char ** outbuffer; /* target buffer */ unsigned long * outsize; unsigned char * newbuffer; /* newly allocated buffer */ JOCTET * buffer; /* start of buffer */ size_t bufsize; } my_mem_destination_mgr; typedef my_mem_destination_mgr * my_mem_dest_ptr; void init_mem_destination (j_compress_ptr cinfo) { /* no work necessary here */ } boolean empty_mem_output_buffer (j_compress_ptr cinfo) { size_t nextsize; JOCTET * nextbuffer; my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; /* Try to allocate new buffer with double size */ nextsize = dest->bufsize * 2; nextbuffer = (JOCTET *)malloc(nextsize); if (nextbuffer == NULL) throw "malloc failed in empty_mem_output_buffer"; memcpy(nextbuffer, dest->buffer, dest->bufsize); if (dest->newbuffer != NULL) free(dest->newbuffer); dest->newbuffer = nextbuffer; dest->pub.next_output_byte = nextbuffer + dest->bufsize; dest->pub.free_in_buffer = dest->bufsize; dest->buffer = nextbuffer; dest->bufsize = nextsize; return TRUE; } void term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; } void jpeg_mem_dest (j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize) { my_mem_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_mem_dest. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_mem_destination_mgr)); } dest = (my_mem_dest_ptr) cinfo->dest; dest->pub.init_destination = init_mem_destination; dest->pub.empty_output_buffer = empty_mem_output_buffer; dest->pub.term_destination = term_mem_destination; dest->outbuffer = outbuffer; dest->outsize = outsize; dest->newbuffer = NULL; if (*outbuffer == NULL || *outsize == 0) { /* Allocate initial buffer */ dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE); if (dest->newbuffer == NULL) throw "out of memory in jpeg_mem_dest (copied implementation)"; *outsize = OUTPUT_BUF_SIZE; } dest->pub.next_output_byte = dest->buffer = *outbuffer; dest->pub.free_in_buffer = dest->bufsize = *outsize; } #endif void JpegEncoder::encode() { + + + clock_t t = clock(); + struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); cinfo.smoothing_factor = smoothing; jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; switch (buf_type) { case BUF_RGBA: rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; break; case BUF_BGRA: rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; break; case BUF_BGR: rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; break; case BUF_RGB: rgb_data = data; break; default: throw "Unexpected buf_type in JpegEncoder::encode"; } JSAMPROW row_pointer; int start = 0; if (!offset.isNull()) { start = offset.y*width*3 + offset.x*3; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_BGR || buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); + + t = clock() - t; + printf ("encode( took %d clicks (%f ms).\n",(int)t,((float)(t*1000))/CLOCKS_PER_SEC); } void JpegEncoder::set_quality(int q) { quality = q; } void JpegEncoder::set_smoothing(int ssmoothing) { smoothing = ssmoothing; } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; }
pkrumins/node-jpeg
410331853192bb75692d2b7ad6d1a1429d0ae8cc
Added smoothing option
diff --git a/src/jpeg.cpp b/src/jpeg.cpp index 3231756..cf0a0eb 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,232 +1,262 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); + NODE_SET_PROTOTYPE_METHOD(t, "setSmoothing", SetSmoothing); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder(ddata, wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } +void +Jpeg::SetSmoothing(int s) +{ + jpeg_encoder.set_smoothing(s); +} + Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Local<Object> buffer = args[0]->ToObject(); Jpeg *jpeg = new Jpeg((unsigned char*) Buffer::Data(buffer), w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } +v8::Handle<v8::Value> Jpeg::SetSmoothing(const v8::Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - quality"); + + if (!args[0]->IsInt32()) + return VException("First argument must be integer quality"); + + int s = args[0]->Int32Value(); + + if (s < 0) + return VException("Smoothing must be greater or equal to 0."); + if (s > 100) + return VException("Smoothing must be less than or equal to 100."); + + Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); + jpeg->SetSmoothing(s); + + return Undefined(); +} + void Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/jpeg.h b/src/jpeg.h index d371d00..c60b809 100644 --- a/src/jpeg.h +++ b/src/jpeg.h @@ -1,27 +1,29 @@ #ifndef JPEG_H #define JPEG_H #include <node.h> #include <node_buffer.h> #include "jpeg_encoder.h" class Jpeg : public node::ObjectWrap { JpegEncoder jpeg_encoder; static void EIO_JpegEncode(eio_req *req); static int EIO_JpegEncodeAfter(eio_req *req); public: static void Initialize(v8::Handle<v8::Object> target); Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncodeSync(); void SetQuality(int q); + void SetSmoothing(int s); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); + static v8::Handle<v8::Value> SetSmoothing(const v8::Arguments &args); }; #endif diff --git a/src/jpeg_encoder.cpp b/src/jpeg_encoder.cpp index 97aa948..0ff82de 100644 --- a/src/jpeg_encoder.cpp +++ b/src/jpeg_encoder.cpp @@ -1,204 +1,210 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : - data(ddata), width(wwidth), height(hheight), quality(qquality), + data(ddata), width(wwidth), height(hheight), quality(qquality), smoothing(0), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } #if JPEG_LIB_VERSION < 80 // copied over from latest libjpeg #define OUTPUT_BUF_SIZE 4096 typedef struct { struct jpeg_destination_mgr pub; /* public fields */ unsigned char ** outbuffer; /* target buffer */ unsigned long * outsize; unsigned char * newbuffer; /* newly allocated buffer */ JOCTET * buffer; /* start of buffer */ size_t bufsize; } my_mem_destination_mgr; typedef my_mem_destination_mgr * my_mem_dest_ptr; void init_mem_destination (j_compress_ptr cinfo) { /* no work necessary here */ } boolean empty_mem_output_buffer (j_compress_ptr cinfo) { size_t nextsize; JOCTET * nextbuffer; my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; /* Try to allocate new buffer with double size */ nextsize = dest->bufsize * 2; nextbuffer = (JOCTET *)malloc(nextsize); if (nextbuffer == NULL) throw "malloc failed in empty_mem_output_buffer"; memcpy(nextbuffer, dest->buffer, dest->bufsize); if (dest->newbuffer != NULL) free(dest->newbuffer); dest->newbuffer = nextbuffer; dest->pub.next_output_byte = nextbuffer + dest->bufsize; dest->pub.free_in_buffer = dest->bufsize; dest->buffer = nextbuffer; dest->bufsize = nextsize; return TRUE; } void term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; } void jpeg_mem_dest (j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize) { my_mem_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_mem_dest. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_mem_destination_mgr)); } dest = (my_mem_dest_ptr) cinfo->dest; dest->pub.init_destination = init_mem_destination; dest->pub.empty_output_buffer = empty_mem_output_buffer; dest->pub.term_destination = term_mem_destination; dest->outbuffer = outbuffer; dest->outsize = outsize; dest->newbuffer = NULL; if (*outbuffer == NULL || *outsize == 0) { /* Allocate initial buffer */ dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE); if (dest->newbuffer == NULL) throw "out of memory in jpeg_mem_dest (copied implementation)"; *outsize = OUTPUT_BUF_SIZE; } dest->pub.next_output_byte = dest->buffer = *outbuffer; dest->pub.free_in_buffer = dest->bufsize = *outsize; } #endif void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); + cinfo.smoothing_factor = smoothing; jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; switch (buf_type) { case BUF_RGBA: rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; break; case BUF_BGRA: rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; break; case BUF_BGR: rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; break; case BUF_RGB: rgb_data = data; break; default: throw "Unexpected buf_type in JpegEncoder::encode"; } JSAMPROW row_pointer; int start = 0; if (!offset.isNull()) { start = offset.y*width*3 + offset.x*3; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_BGR || buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } void JpegEncoder::set_quality(int q) { quality = q; } +void JpegEncoder::set_smoothing(int ssmoothing) +{ + smoothing = ssmoothing; +} + const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; } diff --git a/src/jpeg_encoder.h b/src/jpeg_encoder.h index 7d7528c..1397736 100644 --- a/src/jpeg_encoder.h +++ b/src/jpeg_encoder.h @@ -1,33 +1,34 @@ #ifndef JPEG_ENCODER_H #define JPEG_ENCODER_H #include <cstdio> #include <cstdlib> #include <jpeglib.h> #include "common.h" class JpegEncoder { - int width, height, quality; + int width, height, quality, smoothing; buffer_type buf_type; unsigned char *data; unsigned char *jpeg; long unsigned int jpeg_len; Rect offset; public: JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type); ~JpegEncoder(); void encode(); void set_quality(int qquality); + void set_smoothing(int ssmoothing); const unsigned char *get_jpeg() const; unsigned int get_jpeg_len() const; void setRect(const Rect &r); }; #endif
pkrumins/node-jpeg
55fa704d722b7afbfbca561cbba8178509ceb89e
bump to v1.0.2
diff --git a/package.json b/package.json index ccf4e9f..18e2b8e 100644 --- a/package.json +++ b/package.json @@ -1,35 +1,35 @@ { "name": "jpeg", - "version": "1.0.1", + "version": "1.0.2", "main": "build/Release/jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "author": { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" }, "license": "MIT", "repository": { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" }, "directories": { "examples": "examples", "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-waf configure build" } }
pkrumins/node-jpeg
4f19eac298ec3eab451a788f45394a6d83c00815
bump to v1.0.1
diff --git a/package.json b/package.json index 017cc89..896f474 100644 --- a/package.json +++ b/package.json @@ -1,35 +1,35 @@ { "name": "jpeg", - "version": "1.0.0", + "version": "1.0.1", "main": "build/Release/jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "author": { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" }, "license": "MIT", "repository": { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" } "directories": { "examples": "examples", "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-waf configure build" } }
pkrumins/node-jpeg
ea0e11391df942792e76e6002d5dce60b67b1037
fix buffer unwraps
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index 66afd10..77058a6 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,478 +1,478 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); - Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + Local<Object> data_buf = args[0]->ToObject(); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)Buffer::Data(data_buf), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); - Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + Local<Object> data_buf = args[0]->ToObject(); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)Buffer::Data(data_buf), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } void DynamicJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; try { Rect &dyn_rect = jpeg->dyn_rect; JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; Handle<Value> argv[3]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = Undefined(); argv[2] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = jpeg->Dimensions(); argv[2] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); jpeg->Unref(); free(enc_req); return 0; } Handle<Value> DynamicJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
b1f2b69e98ab198832310292fbf43e127ae35b68
BufferData -> Buffer::Data
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index 949c248..66afd10 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,478 +1,478 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); - memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); + memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); - jpeg->Push((unsigned char *)BufferData(data_buf), x, y, w, h); + jpeg->Push((unsigned char *)Buffer::Data(data_buf), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { - jpeg->SetBackground((unsigned char *)BufferData(data_buf), w, h); + jpeg->SetBackground((unsigned char *)Buffer::Data(data_buf), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } void DynamicJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; try { Rect &dyn_rect = jpeg->dyn_rect; JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; Handle<Value> argv[3]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = Undefined(); argv[2] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); - memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); + memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = jpeg->Dimensions(); argv[2] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); jpeg->Unref(); free(enc_req); return 0; } Handle<Value> DynamicJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
df3f6b0c5e264602491e64cb2a670504e3cffa85
no longer use ObjectWrap::Unwrap for Buffer
diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index 4ff291a..ed75fe1 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,343 +1,343 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); - Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + Local<Object> data_buf = args[0]->ToObject(); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)Buffer::Data(data_buf), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } void FixedJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; try { JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> FixedJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
a0fd478aaf586299097900c746bca879cf0ef2bd
BufferData -> Buffer::Data
diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index 56be937..4ff291a 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,343 +1,343 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); - memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); + memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); - jpeg->Push((unsigned char *)BufferData(data_buf), x, y, w, h); + jpeg->Push((unsigned char *)Buffer::Data(data_buf), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } void FixedJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; try { JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); - memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); + memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> FixedJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
a75bfe0d05629ac9bd870bd357c201abad76e698
add cast to unsigned char*
diff --git a/src/jpeg.cpp b/src/jpeg.cpp index dbd5c12..3231756 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,232 +1,232 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder(ddata, wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Local<Object> buffer = args[0]->ToObject(); - Jpeg *jpeg = new Jpeg(Buffer::Data(buffer), w, h, buf_type); + Jpeg *jpeg = new Jpeg((unsigned char*) Buffer::Data(buffer), w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } void Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
c561defef9328befc5103320f5849e8c5648c06c
fix conflicting declaration
diff --git a/src/jpeg.cpp b/src/jpeg.cpp index 6f2c0c8..dbd5c12 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,232 +1,232 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder(ddata, wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } - Local<Object> jpeg = args[0]->ToObject(); - Jpeg *jpeg = new Jpeg(Buffer::Data(jpeg), w, h, buf_type); + Local<Object> buffer = args[0]->ToObject(); + Jpeg *jpeg = new Jpeg(Buffer::Data(buffer), w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } void Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
af82a61d7d52effe060c30fc7f4489a6d8c8d02e
make Jpeg compatible to node 6
diff --git a/src/jpeg.cpp b/src/jpeg.cpp index 1d3c418..6f2c0c8 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,232 +1,232 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } -Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : - jpeg_encoder((unsigned char *)Buffer::Data(ddata), wwidth, hheight, 60, bbuf_type) {} +Jpeg::Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type) : + jpeg_encoder(ddata, wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } - Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); - Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); + Local<Object> jpeg = args[0]->ToObject(); + Jpeg *jpeg = new Jpeg(Buffer::Data(jpeg), w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } void Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/jpeg.h b/src/jpeg.h index 40d2a35..d371d00 100644 --- a/src/jpeg.h +++ b/src/jpeg.h @@ -1,27 +1,27 @@ #ifndef JPEG_H #define JPEG_H #include <node.h> #include <node_buffer.h> #include "jpeg_encoder.h" class Jpeg : public node::ObjectWrap { JpegEncoder jpeg_encoder; static void EIO_JpegEncode(eio_req *req); static int EIO_JpegEncodeAfter(eio_req *req); public: static void Initialize(v8::Handle<v8::Object> target); - Jpeg(node::Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type); + Jpeg(unsigned char *ddata, int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncodeSync(); void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif
pkrumins/node-jpeg
d561a09fc6ab5ab7a0415c3b239eee12878d490a
BufferData -> Buffer::Data
diff --git a/src/jpeg.cpp b/src/jpeg.cpp index 625597a..1d3c418 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,232 +1,232 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : - jpeg_encoder((unsigned char *)BufferData(ddata), wwidth, hheight, 60, bbuf_type) {} + jpeg_encoder((unsigned char *)Buffer::Data(ddata), wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); - memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); + memcpy(Buffer::Data(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } void Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); - memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); + memcpy(Buffer::Data(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
00352513f9d3be690c20e8727c9279c4e18f24c2
point main in package json to right location of compiled module
diff --git a/package.json b/package.json index 2c61ebd..2e46206 100644 --- a/package.json +++ b/package.json @@ -1,43 +1,43 @@ { "name": "jpeg", "version": "1.0.0", - "main": "jpeg", + "main": "build/Release/jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "maintainers": [ { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" } ], "licenses": [ { "type": "MIT" } ], "repositories": [ { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" } ], "directories": { "examples": "examples", "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-waf configure build" } }
pkrumins/node-jpeg
4a73ef5d6892970183875c8f60754d9202c7f043
adapt to change in `eio_custom` signature
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index 9554ddb..949c248 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,480 +1,478 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)BufferData(data_buf), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)BufferData(data_buf), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } -int +void DynamicJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; try { Rect &dyn_rect = jpeg->dyn_rect; JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); - return 0; + return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } - - return 0; } int DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; Handle<Value> argv[3]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = Undefined(); argv[2] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = jpeg->Dimensions(); argv[2] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); jpeg->Unref(); free(enc_req); return 0; } Handle<Value> DynamicJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h index 0939344..dae3672 100644 --- a/src/dynamic_jpeg_stack.h +++ b/src/dynamic_jpeg_stack.h @@ -1,49 +1,49 @@ #ifndef DYNAMIC_JPEG_H #define DYNAMIC_JPEG_H #include <node.h> #include <node_buffer.h> #include <vector> #include <utility> #include "common.h" #include "jpeg_encoder.h" class DynamicJpegStack : public node::ObjectWrap { int quality; buffer_type buf_type; unsigned char *data; int bg_width, bg_height; // background width and height after setBackground Rect dyn_rect; // rect of dynamic push area (updated after each push) void update_optimal_dimension(int x, int y, int w, int h); - static int EIO_JpegEncode(eio_req *req); + static void EIO_JpegEncode(eio_req *req); static int EIO_JpegEncodeAfter(eio_req *req); public: DynamicJpegStack(buffer_type bbuf_type); ~DynamicJpegStack(); v8::Handle<v8::Value> JpegEncodeSync(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetBackground(unsigned char *data_buf, int w, int h); void SetQuality(int q); v8::Handle<v8::Value> Dimensions(); void Reset(); static void Initialize(v8::Handle<v8::Object> target); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); static v8::Handle<v8::Value> Reset(const v8::Arguments &args); }; #endif diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index 4794914..56be937 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,345 +1,343 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)BufferData(data_buf), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } -int +void FixedJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; try { JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); - return 0; + return; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } - - return 0; } int FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> FixedJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/fixed_jpeg_stack.h b/src/fixed_jpeg_stack.h index ab24109..849505a 100644 --- a/src/fixed_jpeg_stack.h +++ b/src/fixed_jpeg_stack.h @@ -1,34 +1,34 @@ #ifndef STACKED_JPEG_H #define STACKED_JPEG_H #include <node.h> #include <node_buffer.h> #include "common.h" #include "jpeg_encoder.h" class FixedJpegStack : public node::ObjectWrap { int width, height, quality; buffer_type buf_type; unsigned char *data; - static int EIO_JpegEncode(eio_req *req); + static void EIO_JpegEncode(eio_req *req); static int EIO_JpegEncodeAfter(eio_req *req); public: static void Initialize(v8::Handle<v8::Object> target); FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncodeSync(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif diff --git a/src/jpeg.cpp b/src/jpeg.cpp index 631d6fc..625597a 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,234 +1,232 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" #include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder((unsigned char *)BufferData(ddata), wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } -int +void Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); - return 0; + return; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } - - return 0; } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/jpeg.h b/src/jpeg.h index e734c18..40d2a35 100644 --- a/src/jpeg.h +++ b/src/jpeg.h @@ -1,27 +1,27 @@ #ifndef JPEG_H #define JPEG_H #include <node.h> #include <node_buffer.h> #include "jpeg_encoder.h" class Jpeg : public node::ObjectWrap { JpegEncoder jpeg_encoder; - static int EIO_JpegEncode(eio_req *req); + static void EIO_JpegEncode(eio_req *req); static int EIO_JpegEncodeAfter(eio_req *req); public: static void Initialize(v8::Handle<v8::Object> target); Jpeg(node::Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncodeSync(); void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif
pkrumins/node-jpeg
477a84c1d1e53ae6caf991b9cfcb2ba42062ffa9
integrated buffer helpers
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index 8969ce5..9554ddb 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,479 +1,480 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" +#include "buffer_compat.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); - memcpy(retbuf->data(), jpeg_encoder.get_jpeg(), jpeg_len); + memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); - jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); + jpeg->Push((unsigned char *)BufferData(data_buf), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { - jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); + jpeg->SetBackground((unsigned char *)BufferData(data_buf), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } int DynamicJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; try { Rect &dyn_rect = jpeg->dyn_rect; JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); return 0; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } return 0; } int DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; Handle<Value> argv[3]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = Undefined(); argv[2] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); - memcpy(buf->data(), enc_req->jpeg, enc_req->jpeg_len); + memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = jpeg->Dimensions(); argv[2] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); jpeg->Unref(); free(enc_req); return 0; } Handle<Value> DynamicJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index 105feb2..4794914 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,344 +1,345 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" +#include "buffer_compat.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); - memcpy(retbuf->data(), jpeg_encoder.get_jpeg(), jpeg_len); + memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); - jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); + jpeg->Push((unsigned char *)BufferData(data_buf), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } int FixedJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; try { JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); return 0; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } return 0; } int FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); - memcpy(buf->data(), enc_req->jpeg, enc_req->jpeg_len); + memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> FixedJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); } diff --git a/src/jpeg.cpp b/src/jpeg.cpp index e2518a6..631d6fc 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,233 +1,234 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" +#include "buffer_compat.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : - jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, 60, bbuf_type) {} + jpeg_encoder((unsigned char *)BufferData(ddata), wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } int jpeg_len = jpeg_encoder.get_jpeg_len(); Buffer *retbuf = Buffer::New(jpeg_len); - memcpy(retbuf->data(), jpeg_encoder.get_jpeg(), jpeg_len); + memcpy(BufferData(retbuf), jpeg_encoder.get_jpeg(), jpeg_len); return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } int Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return 0; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } return 0; } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { Buffer *buf = Buffer::New(enc_req->jpeg_len); - memcpy(buf->data(), enc_req->jpeg, enc_req->jpeg_len); + memcpy(BufferData(buf), enc_req->jpeg, enc_req->jpeg_len); argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
b86cfa653586e247bd5bd889990056d22af771a9
added buffer compatibility helpers to avoid node version conflicts
diff --git a/src/buffer_compat.cpp b/src/buffer_compat.cpp new file mode 100644 index 0000000..24dac9c --- /dev/null +++ b/src/buffer_compat.cpp @@ -0,0 +1,58 @@ +#include <node.h> +#include <node_buffer.h> +#include <node_version.h> +#include <v8.h> +#include "buffer_compat.h" + + +#if NODE_MINOR_VERSION < 3 + + +char *BufferData(node::Buffer *b) { + return b->data(); +} + + +size_t BufferLength(node::Buffer *b) { + return b->length(); +} + + +char *BufferData(v8::Local<v8::Object> buf_obj) { + v8::HandleScope scope; + node::Buffer *buf = node::ObjectWrap::Unwrap<node::Buffer>(buf_obj); + return buf->data(); +} + + +size_t BufferLength(v8::Local<v8::Object> buf_obj) { + v8::HandleScope scope; + node::Buffer *buf = node::ObjectWrap::Unwrap<node::Buffer>(buf_obj); + return buf->length(); +} + +#else // NODE_VERSION + + +char *BufferData(node::Buffer *b) { + return node::Buffer::Data(b->handle_); +} + + +size_t BufferLength(node::Buffer *b) { + return node::Buffer::Length(b->handle_); +} + + +char *BufferData(v8::Local<v8::Object> buf_obj) { + v8::HandleScope scope; + return node::Buffer::Data(buf_obj); +} + + +size_t BufferLength(v8::Local<v8::Object> buf_obj) { + v8::HandleScope scope; + return node::Buffer::Length(buf_obj); +} + +#endif // NODE_VERSION diff --git a/src/buffer_compat.h b/src/buffer_compat.h new file mode 100644 index 0000000..fa7c61c --- /dev/null +++ b/src/buffer_compat.h @@ -0,0 +1,15 @@ +#ifndef buffer_compat_h +#define buffer_compat_h + +#include <node.h> +#include <node_buffer.h> +#include <v8.h> + +char *BufferData(node::Buffer *b); +size_t BufferLength(node::Buffer *b); + +char *BufferData(v8::Local<v8::Object> buf_obj); +size_t BufferLength(v8::Local<v8::Object> buf_obj); + + +#endif // buffer_compat_h
pkrumins/node-jpeg
25f5f8509f1079743555b6eec2a3867f38d06ba0
wrote a very cursory documentation of FixedJpegStack and DynamicJpegStack
diff --git a/readme.txt b/readme.txt index b5215a3..65334ac 100644 --- a/readme.txt +++ b/readme.txt @@ -1,39 +1,126 @@ This is a node.js module, writen in C++, that uses libjpeg to produce a JPEG image (in memory) from a buffer of RGBA or RGB values. Since JPEG has no notion of A (alpha), the module always uses just RGB values. It was written by Peteris Krumins ([email protected]). His blog is at http://www.catonmat.net -- good coders code, great reuse. ------------------------------------------------------------------------------ -The module exports `Jpeg` object that takes 5 arguments in its constructor: +The module exports three objects: Jpeg, FixedJpegStack, DynamicJpegStack. - var png = new Jpeg(buffer, width, height, quality, buffer_type); +Jpeg allows to create fixed size jpegs from RGB, BGR, RGBA or BGRA buffers. +FixedJpegStack allows to push multiple jpegs to a fixed size canvas. +DynamicJpegStack allows to push multiple jpegs to a dynamic size canvas (it +grows as you push jpegs to it). + +All objects provide synchronous and asynchronous interfaces. + +Jpeg +---- + +Jpeg object that takes 4 arguments in its constructor: + + var jpeg = new Jpeg(buffer, width, height, [buffer_type]); The first argument, `buffer`, is a nodee.js `Buffer` filled with RGBA or RGB values. The second argument is integer width of the image. The third argument is integer height of the image. -The fourth argument is the quality of output image. -The fifth argument is buffer type, either 'rgb' or 'rgba'. +The fourth argument is buffer type, either 'rgb' or 'rgba'. [Optional]. + +After you have constructed the object, call .encode() or .encodeSync to produce +a jpeg: + + var jpeg_image = jpeg.encodeSync(); // synchronous encoding (blocks node.js) + +Or: + + jpeg.encode(function (image, error) { + // jpeg image is in 'image' + }); See `examples/` directory for examples. + +FixedJpegStack +-------------- + +First you create a FixedJpegStack object of fixed width and height: + + var stack = new FixedJpegStack(width, height, [buffer_type]); + +Then you can push individual fragments to it, for example, + + stack.push(buf1, 10, 11, 100, 200); // pushes buf1 to (x,y)=(10,11) + // 100 and 200 are width and height. + + // more pushes + +After you're done, call .encode() to produce final jpeg asynchronously or +.encodeSync() (just like in Jpeg object). The final jpeg will be of size +width x height. + + +DynamicJpegStack +---------------- + +DynamicJpegStack is the same as FixedJpegStack except its canvas grows dynamically. + +First, create the stack: + + var stack = new DynamicJpegStack([buffer_type]); + +Next push the RGB(A) buffers to it: + + stack.push(buf1, 5, 10, 100, 40); + stack.push(buf2, 2, 210, 20, 20); + +Now you can call `encode` to produce the final jpeg: + + var jpeg = stack.encodeSync(); + +Now let's see what the dimensions are, + + var dims = stack.dimensions(); + +Same asynchronously: + + stack.encode(function (jpeg, dims) { + // jpeg is the image + // dims are its dimensions + }); + +In this particular example: + +The x position `dims.x` is 2 because the 2nd jpeg is closer to the left. +The y position `dims.y` is 10 because the 1st jpeg is closer to the top. +The width `dims.width` is 103 because the first jpeg stretches from x=5 to +x=105, but the 2nd jpeg starts only at x=2, so the first two pixels are not +necessary and the width is 105-2=103. +The height `dims.height` is 220 because the 2nd jpeg is located at 210 and +its height is 20, so it stretches to position 230, but the first jpeg starts +at 10, so the upper 10 pixels are not necessary and height becomes 230-10= 220. + + +How to install? +--------------- + To get it compiled, you need to have libjpeg and node installed. Then just run node-waf configure build to build the Jpeg module. It will produce a `jpeg.node` file as the module. See also http://github.com/pkrumins/node-png module that produces PNG images. +See also http://github.com/pkrumins/node-gif module that produces GIF images. ------------------------------------------------------------------------------ Have fun! Sincerely, Peteris Krumins http://www.catonmat.net
pkrumins/node-jpeg
7090e1bbb2075aa09e41381b866db72b591fa9be
DynamicJpegStack now returns Buffer
diff --git a/examples/dynamic-jpeg-stack-async.js b/examples/dynamic-jpeg-stack-async.js index 114bea2..90b43e3 100644 --- a/examples/dynamic-jpeg-stack-async.js +++ b/examples/dynamic-jpeg-stack-async.js @@ -1,35 +1,33 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; // -------- var terminal = fs.readFileSync('./rgba-terminal.dat'); var jpegStack = new JpegLib.DynamicJpegStack('rgba'); jpegStack.setBackground(terminal, 720, 400); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); - var rgba = fs.readFileSync('./push-data/' + file, 'binary'); - var buf = new Buffer(rgba.length); - buf.write(rgba, 'binary'); - jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); + var rgba = fs.readFileSync('./push-data/' + file); + jpegStack.push(rgba, dim.x, dim.y, dim.w, dim.h); }); jpegStack.encode(function (image, dims) { - fs.writeFileSync('dynamic-async.jpg', image, 'binary'); + fs.writeFileSync('dynamic-async.jpg', image.toString('binary'), 'binary'); sys.puts("x: " + dims.x + ", y: " + dims.y + ", w: " + dims.width + ", h: " + dims.height); }); diff --git a/examples/dynamic-jpeg-stack.js b/examples/dynamic-jpeg-stack.js index 12524d2..bf05b53 100644 --- a/examples/dynamic-jpeg-stack.js +++ b/examples/dynamic-jpeg-stack.js @@ -1,35 +1,33 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; // -------- var terminal = fs.readFileSync('./rgba-terminal.dat'); var jpegStack = new JpegLib.DynamicJpegStack('rgba'); jpegStack.setBackground(terminal, 720, 400); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); - var rgba = fs.readFileSync('./push-data/' + file, 'binary'); - var buf = new Buffer(rgba.length); - buf.write(rgba, 'binary'); - jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); + var rgba = fs.readFileSync('./push-data/' + file); + jpegStack.push(rgba, dim.x, dim.y, dim.w, dim.h); }); -fs.writeFileSync('dynamic.jpg', jpegStack.encodeSync(), 'binary'); +fs.writeFileSync('dynamic.jpg', jpegStack.encodeSync().toString('binary'), 'binary'); var dims = jpegStack.dimensions(); sys.puts("x: " + dims.x + ", y: " + dims.y + ", w: " + dims.width + ", h: " + dims.height); diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index 0f06c04..8969ce5 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,476 +1,479 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); - return scope.Close( - Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) - ); + int jpeg_len = jpeg_encoder.get_jpeg_len(); + Buffer *retbuf = Buffer::New(jpeg_len); + memcpy(retbuf->data(), jpeg_encoder.get_jpeg(), jpeg_len); + return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } int DynamicJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; try { Rect &dyn_rect = jpeg->dyn_rect; JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); return 0; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } return 0; } int DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; Handle<Value> argv[3]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = Undefined(); argv[2] = ErrorException(enc_req->error); } else { - argv[0] = Local<Value>::New(Encode(enc_req->jpeg, enc_req->jpeg_len, BINARY)); + Buffer *buf = Buffer::New(enc_req->jpeg_len); + memcpy(buf->data(), enc_req->jpeg, enc_req->jpeg_len); + argv[0] = buf->handle_; argv[1] = jpeg->Dimensions(); argv[2] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); jpeg->Unref(); free(enc_req); return 0; } Handle<Value> DynamicJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
1b2ac0c36b64ee00a5eea07893e74422de275124
FixedJpegStack now returns Buffer
diff --git a/examples/fixed-jpeg-stack-async.js b/examples/fixed-jpeg-stack-async.js index 40f34a0..e8c8da7 100644 --- a/examples/fixed-jpeg-stack-async.js +++ b/examples/fixed-jpeg-stack-async.js @@ -1,29 +1,27 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; var jpegStack = new JpegLib.FixedJpegStack(720, 400, 'rgba'); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); - var rgba = fs.readFileSync('./push-data/' + file, 'binary'); - var buf = new Buffer(rgba.length); - buf.write(rgba, 'binary'); - jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); + var rgba = fs.readFileSync('./push-data/' + file); + jpegStack.push(rgba, dim.x, dim.y, dim.w, dim.h); }); jpegStack.encode(function (image) { - fs.writeFileSync('fixed-async.jpg', image, 'binary'); + fs.writeFileSync('fixed-async.jpg', image.toString('binary'), 'binary'); }); diff --git a/examples/fixed-jpeg-stack.js b/examples/fixed-jpeg-stack.js index 64741fa..0af0f73 100644 --- a/examples/fixed-jpeg-stack.js +++ b/examples/fixed-jpeg-stack.js @@ -1,27 +1,25 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; var jpegStack = new JpegLib.FixedJpegStack(720, 400, 'rgba'); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); - var rgba = fs.readFileSync('./push-data/' + file, 'binary'); - var buf = new Buffer(rgba.length); - buf.write(rgba, 'binary'); - jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); + var rgba = fs.readFileSync('./push-data/' + file); + jpegStack.push(rgba, dim.x, dim.y, dim.w, dim.h); }); -fs.writeFileSync('fixed.jpg', jpegStack.encodeSync(), 'binary'); +fs.writeFileSync('fixed.jpg', jpegStack.encodeSync().toString('binary'), 'binary'); diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index fdc88d5..105feb2 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,341 +1,344 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); - return scope.Close( - Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) - ); + int jpeg_len = jpeg_encoder.get_jpeg_len(); + Buffer *retbuf = Buffer::New(jpeg_len); + memcpy(retbuf->data(), jpeg_encoder.get_jpeg(), jpeg_len); + return scope.Close(retbuf->handle_); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } int FixedJpegStack::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; try { JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); encoder.encode(); enc_req->jpeg_len = encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); return 0; } else { memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } return 0; } int FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { - argv[0] = Local<Value>::New(Encode(enc_req->jpeg, enc_req->jpeg_len, BINARY)); + Buffer *buf = Buffer::New(enc_req->jpeg_len); + memcpy(buf->data(), enc_req->jpeg, enc_req->jpeg_len); + argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> FixedJpegStack::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
7104754541637d7f56dfc20984235433860d7704
Jpeg now returns Buffer
diff --git a/examples/jpeg-example-async.js b/examples/jpeg-example-async.js index 477feb8..4553cff 100644 --- a/examples/jpeg-example-async.js +++ b/examples/jpeg-example-async.js @@ -1,14 +1,12 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; -// the rgba-terminal.dat file is 1152000 bytes long. -var rgba = new Buffer(1152000); -rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); +var rgba = fs.readFileSync('./rgba-terminal.dat'); var jpeg = new Jpeg(rgba, 720, 400, 'rgba'); jpeg.encode(function (image) { - fs.writeFileSync('./jpeg-async.jpeg', image, 'binary'); + fs.writeFileSync('./jpeg-async.jpeg', image.toString('binary'), 'binary'); }) diff --git a/examples/jpeg-example.js b/examples/jpeg-example.js index 3deae6f..a12ab62 100644 --- a/examples/jpeg-example.js +++ b/examples/jpeg-example.js @@ -1,14 +1,12 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; -// the rgba-terminal.dat file is 1152000 bytes long. -var rgba = new Buffer(1152000); -rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); +var rgba = fs.readFileSync('./rgba-terminal.dat'); var jpeg = new Jpeg(rgba, 720, 400, 'rgba'); -var jpeg_img = jpeg.encodeSync(); +var jpeg_img = jpeg.encodeSync().toString('binary'); fs.writeFileSync('./jpeg.jpeg', jpeg_img, 'binary'); diff --git a/examples/jpeg-example2-async.js b/examples/jpeg-example2-async.js index 12c67f6..dd04e6c 100644 --- a/examples/jpeg-example2-async.js +++ b/examples/jpeg-example2-async.js @@ -1,22 +1,22 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; var WIDTH = 400, HEIGHT = 300; var rgba = new Buffer(WIDTH*HEIGHT*3); for (var i=0; i<HEIGHT; i++) { for (var j=0; j<WIDTH; j++) { rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; } } var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 'rgb'); -var jpeg_img = jpeg.encode(); - -fs.writeFileSync('./jpeg-gradient.jpeg', jpeg_img, 'binary'); +jpeg.encode(function (jpeg_img) { + fs.writeFileSync('./jpeg-gradient-async.jpeg', jpeg_img.toString('binary'), 'binary'); +}); diff --git a/examples/jpeg-example2.js b/examples/jpeg-example2.js index 3e78d1e..26a1f11 100644 --- a/examples/jpeg-example2.js +++ b/examples/jpeg-example2.js @@ -1,22 +1,22 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; var WIDTH = 400, HEIGHT = 300; var rgba = new Buffer(WIDTH*HEIGHT*3); for (var i=0; i<HEIGHT; i++) { for (var j=0; j<WIDTH; j++) { rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; } } var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 'rgb'); -var jpeg_img = jpeg.encodeSync(); +var jpeg_img = jpeg.encodeSync().toString('binary'); fs.writeFileSync('./jpeg-gradient.jpeg', jpeg_img, 'binary'); diff --git a/src/jpeg.cpp b/src/jpeg.cpp index d9ce62d..e2518a6 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,230 +1,233 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } - return scope.Close( - Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) - ); + int jpeg_len = jpeg_encoder.get_jpeg_len(); + Buffer *retbuf = Buffer::New(jpeg_len); + memcpy(retbuf->data(), jpeg_encoder.get_jpeg(), jpeg_len); + return scope.Close(retbuf->handle_); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } int Jpeg::EIO_JpegEncode(eio_req *req) { encode_request *enc_req = (encode_request *)req->data; Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; try { jpeg->jpeg_encoder.encode(); enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); if (!enc_req->jpeg) { enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); return 0; } else { memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); } } catch (const char *err) { enc_req->error = strdup(err); } return 0; } int Jpeg::EIO_JpegEncodeAfter(eio_req *req) { HandleScope scope; ev_unref(EV_DEFAULT_UC); encode_request *enc_req = (encode_request *)req->data; Handle<Value> argv[2]; if (enc_req->error) { argv[0] = Undefined(); argv[1] = ErrorException(enc_req->error); } else { - argv[0] = Local<Value>::New(Encode(enc_req->jpeg, enc_req->jpeg_len, BINARY)); + Buffer *buf = Buffer::New(enc_req->jpeg_len); + memcpy(buf->data(), enc_req->jpeg, enc_req->jpeg_len); + argv[0] = buf->handle_; argv[1] = Undefined(); } TryCatch try_catch; // don't quite see the necessity of this enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); enc_req->callback.Dispose(); free(enc_req->jpeg); free(enc_req->error); ((Jpeg *)enc_req->jpeg_obj)->Unref(); free(enc_req); return 0; } Handle<Value> Jpeg::JpegEncodeAsync(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - callback function."); if (!args[0]->IsFunction()) return VException("First argument must be a function."); Local<Function> callback = Local<Function>::Cast(args[0]); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); if (!enc_req) return VException("malloc in Jpeg::JpegEncodeAsync failed."); enc_req->callback = Persistent<Function>::New(callback); enc_req->jpeg_obj = jpeg; enc_req->jpeg = NULL; enc_req->jpeg_len = 0; enc_req->error = NULL; eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); ev_ref(EV_DEFAULT_UC); jpeg->Ref(); return Undefined(); }
pkrumins/node-jpeg
bdf1b7fd027c71e919859fdcf302e5befacd44e7
added async example for dynamic jpeg stack
diff --git a/examples/dynamic-jpeg-stack-async.js b/examples/dynamic-jpeg-stack-async.js new file mode 100644 index 0000000..114bea2 --- /dev/null +++ b/examples/dynamic-jpeg-stack-async.js @@ -0,0 +1,35 @@ +var JpegLib = require('jpeg'); +var fs = require('fs'); +var sys = require('sys'); +var Buffer = require('buffer').Buffer; + +// -------- + +var terminal = fs.readFileSync('./rgba-terminal.dat'); + +var jpegStack = new JpegLib.DynamicJpegStack('rgba'); +jpegStack.setBackground(terminal, 720, 400); + +function rectDim(fileName) { + var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); + var dim = [m[1], m[2], m[3], m[4]].map(function (n) { + return parseInt(n, 10); + }); + return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } +} + +var files = fs.readdirSync('./push-data'); + +files.forEach(function(file) { + var dim = rectDim(file); + var rgba = fs.readFileSync('./push-data/' + file, 'binary'); + var buf = new Buffer(rgba.length); + buf.write(rgba, 'binary'); + jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); +}); + +jpegStack.encode(function (image, dims) { + fs.writeFileSync('dynamic-async.jpg', image, 'binary'); + sys.puts("x: " + dims.x + ", y: " + dims.y + ", w: " + dims.width + ", h: " + dims.height); +}); +
pkrumins/node-jpeg
1a5f26bb3400dfc33616b92e7aa6bd05eac9f273
this example now uses the new encodeSync function
diff --git a/examples/dynamic-jpeg-stack.js b/examples/dynamic-jpeg-stack.js index d100188..12524d2 100644 --- a/examples/dynamic-jpeg-stack.js +++ b/examples/dynamic-jpeg-stack.js @@ -1,35 +1,35 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; // -------- var terminal = fs.readFileSync('./rgba-terminal.dat'); var jpegStack = new JpegLib.DynamicJpegStack('rgba'); jpegStack.setBackground(terminal, 720, 400); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); var rgba = fs.readFileSync('./push-data/' + file, 'binary'); var buf = new Buffer(rgba.length); buf.write(rgba, 'binary'); jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); }); -fs.writeFileSync('dynamic.jpg', jpegStack.encode(), 'binary'); +fs.writeFileSync('dynamic.jpg', jpegStack.encodeSync(), 'binary'); var dims = jpegStack.dimensions(); sys.puts("x: " + dims.x + ", y: " + dims.y + ", w: " + dims.width + ", h: " + dims.height);
pkrumins/node-jpeg
2f94fe9ec7c7c41ab15fdee24eb24d5cb255ced2
dynamic jpeg stack is now async
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index d2416f7..0f06c04 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,376 +1,476 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); - NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); + NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void -DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) +DynamicJpegStack::update_optimal_dimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> -DynamicJpegStack::JpegEncode() +DynamicJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { - UpdateOptimalDimension(x, y, w, h); + update_optimal_dimension(x, y, w, h); int start = y*bg_width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } switch (buf_type) { case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); break; case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; break; default: throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> -DynamicJpegStack::JpegEncode(const Arguments &args) +DynamicJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); - return jpeg->JpegEncode(); + return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } +int +DynamicJpegStack::EIO_JpegEncode(eio_req *req) +{ + encode_request *enc_req = (encode_request *)req->data; + DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; + + try { + Rect &dyn_rect = jpeg->dyn_rect; + JpegEncoder encoder(jpeg->data, jpeg->bg_width, jpeg->bg_height, jpeg->quality, BUF_RGB); + encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); + encoder.encode(); + enc_req->jpeg_len = encoder.get_jpeg_len(); + enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); + if (!enc_req->jpeg) { + enc_req->error = strdup("malloc in DynamicJpegStack::EIO_JpegEncode failed."); + return 0; + } + else { + memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); + } + } + catch (const char *err) { + enc_req->error = strdup(err); + } + + return 0; +} + +int +DynamicJpegStack::EIO_JpegEncodeAfter(eio_req *req) +{ + HandleScope scope; + + ev_unref(EV_DEFAULT_UC); + encode_request *enc_req = (encode_request *)req->data; + DynamicJpegStack *jpeg = (DynamicJpegStack *)enc_req->jpeg_obj; + + Handle<Value> argv[3]; + + if (enc_req->error) { + argv[0] = Undefined(); + argv[1] = Undefined(); + argv[2] = ErrorException(enc_req->error); + } + else { + argv[0] = Local<Value>::New(Encode(enc_req->jpeg, enc_req->jpeg_len, BINARY)); + argv[1] = jpeg->Dimensions(); + argv[2] = Undefined(); + } + + TryCatch try_catch; // don't quite see the necessity of this + + enc_req->callback->Call(Context::GetCurrent()->Global(), 3, argv); + + if (try_catch.HasCaught()) + FatalException(try_catch); + + enc_req->callback.Dispose(); + free(enc_req->jpeg); + free(enc_req->error); + + jpeg->Unref(); + free(enc_req); + + return 0; +} + +Handle<Value> +DynamicJpegStack::JpegEncodeAsync(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - callback function."); + + if (!args[0]->IsFunction()) + return VException("First argument must be a function."); + + Local<Function> callback = Local<Function>::Cast(args[0]); + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + + encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); + if (!enc_req) + return VException("malloc in DynamicJpegStack::JpegEncodeAsync failed."); + + enc_req->callback = Persistent<Function>::New(callback); + enc_req->jpeg_obj = jpeg; + enc_req->jpeg = NULL; + enc_req->jpeg_len = 0; + enc_req->error = NULL; + + eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); + + ev_ref(EV_DEFAULT_UC); + jpeg->Ref(); + + return Undefined(); +} + diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h index 55f2248..0939344 100644 --- a/src/dynamic_jpeg_stack.h +++ b/src/dynamic_jpeg_stack.h @@ -1,46 +1,49 @@ #ifndef DYNAMIC_JPEG_H #define DYNAMIC_JPEG_H #include <node.h> #include <node_buffer.h> #include <vector> #include <utility> #include "common.h" #include "jpeg_encoder.h" class DynamicJpegStack : public node::ObjectWrap { int quality; buffer_type buf_type; unsigned char *data; int bg_width, bg_height; // background width and height after setBackground Rect dyn_rect; // rect of dynamic push area (updated after each push) - void UpdateOptimalDimension(int x, int y, int w, int h); + void update_optimal_dimension(int x, int y, int w, int h); + static int EIO_JpegEncode(eio_req *req); + static int EIO_JpegEncodeAfter(eio_req *req); public: DynamicJpegStack(buffer_type bbuf_type); ~DynamicJpegStack(); - v8::Handle<v8::Value> JpegEncode(); + v8::Handle<v8::Value> JpegEncodeSync(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetBackground(unsigned char *data_buf, int w, int h); void SetQuality(int q); v8::Handle<v8::Value> Dimensions(); void Reset(); static void Initialize(v8::Handle<v8::Object> target); static v8::Handle<v8::Value> New(const v8::Arguments &args); - static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); static v8::Handle<v8::Value> Reset(const v8::Arguments &args); }; #endif
pkrumins/node-jpeg
47b2af14e180823cd9583100583451491e93cc68
add async example and update old example to use the new encodeSync function
diff --git a/examples/fixed-jpeg-stack-async.js b/examples/fixed-jpeg-stack-async.js new file mode 100644 index 0000000..40f34a0 --- /dev/null +++ b/examples/fixed-jpeg-stack-async.js @@ -0,0 +1,29 @@ +var JpegLib = require('jpeg'); +var fs = require('fs'); +var sys = require('sys'); +var Buffer = require('buffer').Buffer; + +var jpegStack = new JpegLib.FixedJpegStack(720, 400, 'rgba'); + +function rectDim(fileName) { + var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); + var dim = [m[1], m[2], m[3], m[4]].map(function (n) { + return parseInt(n, 10); + }); + return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } +} + +var files = fs.readdirSync('./push-data'); + +files.forEach(function(file) { + var dim = rectDim(file); + var rgba = fs.readFileSync('./push-data/' + file, 'binary'); + var buf = new Buffer(rgba.length); + buf.write(rgba, 'binary'); + jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); +}); + +jpegStack.encode(function (image) { + fs.writeFileSync('fixed-async.jpg', image, 'binary'); +}); + diff --git a/examples/fixed-jpeg-stack.js b/examples/fixed-jpeg-stack.js index b156313..64741fa 100644 --- a/examples/fixed-jpeg-stack.js +++ b/examples/fixed-jpeg-stack.js @@ -1,27 +1,27 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; var jpegStack = new JpegLib.FixedJpegStack(720, 400, 'rgba'); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); var rgba = fs.readFileSync('./push-data/' + file, 'binary'); var buf = new Buffer(rgba.length); buf.write(rgba, 'binary'); jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); }); -fs.writeFileSync('fixed.jpg', jpegStack.encode(), 'binary'); +fs.writeFileSync('fixed.jpg', jpegStack.encodeSync(), 'binary');
pkrumins/node-jpeg
0a6559996d0e51222c047b0e5e7bc31b8d72ece7
fixed jpeg stack is now async
diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index 9380b50..fdc88d5 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,246 +1,341 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); - NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); + NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> -FixedJpegStack::JpegEncode() +FixedJpegStack::JpegEncodeSync() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; switch (buf_type) { case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } break; case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } break; case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } break; case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } break; default: throw "Unexpected buf_type in FixedJpegStack::Push"; } } void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> -FixedJpegStack::JpegEncode(const Arguments &args) +FixedJpegStack::JpegEncodeSync(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); - return jpeg->JpegEncode(); + return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); } +int +FixedJpegStack::EIO_JpegEncode(eio_req *req) +{ + encode_request *enc_req = (encode_request *)req->data; + FixedJpegStack *jpeg = (FixedJpegStack *)enc_req->jpeg_obj; + + try { + JpegEncoder encoder(jpeg->data, jpeg->width, jpeg->height, jpeg->quality, BUF_RGB); + encoder.encode(); + enc_req->jpeg_len = encoder.get_jpeg_len(); + enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); + if (!enc_req->jpeg) { + enc_req->error = strdup("malloc in FixedJpegStack::EIO_JpegEncode failed."); + return 0; + } + else { + memcpy(enc_req->jpeg, encoder.get_jpeg(), enc_req->jpeg_len); + } + } + catch (const char *err) { + enc_req->error = strdup(err); + } + + return 0; +} + +int +FixedJpegStack::EIO_JpegEncodeAfter(eio_req *req) +{ + HandleScope scope; + + ev_unref(EV_DEFAULT_UC); + encode_request *enc_req = (encode_request *)req->data; + + Handle<Value> argv[2]; + + if (enc_req->error) { + argv[0] = Undefined(); + argv[1] = ErrorException(enc_req->error); + } + else { + argv[0] = Local<Value>::New(Encode(enc_req->jpeg, enc_req->jpeg_len, BINARY)); + argv[1] = Undefined(); + } + + TryCatch try_catch; // don't quite see the necessity of this + + enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); + + if (try_catch.HasCaught()) + FatalException(try_catch); + + enc_req->callback.Dispose(); + free(enc_req->jpeg); + free(enc_req->error); + + ((FixedJpegStack *)enc_req->jpeg_obj)->Unref(); + free(enc_req); + + return 0; +} + +Handle<Value> +FixedJpegStack::JpegEncodeAsync(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - callback function."); + + if (!args[0]->IsFunction()) + return VException("First argument must be a function."); + + Local<Function> callback = Local<Function>::Cast(args[0]); + FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); + + encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); + if (!enc_req) + return VException("malloc in FixedJpegStack::JpegEncodeAsync failed."); + + enc_req->callback = Persistent<Function>::New(callback); + enc_req->jpeg_obj = jpeg; + enc_req->jpeg = NULL; + enc_req->jpeg_len = 0; + enc_req->error = NULL; + + eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); + + ev_ref(EV_DEFAULT_UC); + jpeg->Ref(); + + return Undefined(); +} + diff --git a/src/fixed_jpeg_stack.h b/src/fixed_jpeg_stack.h index 54783ef..ab24109 100644 --- a/src/fixed_jpeg_stack.h +++ b/src/fixed_jpeg_stack.h @@ -1,30 +1,34 @@ #ifndef STACKED_JPEG_H #define STACKED_JPEG_H #include <node.h> #include <node_buffer.h> #include "common.h" #include "jpeg_encoder.h" class FixedJpegStack : public node::ObjectWrap { int width, height, quality; buffer_type buf_type; unsigned char *data; + static int EIO_JpegEncode(eio_req *req); + static int EIO_JpegEncodeAfter(eio_req *req); + public: static void Initialize(v8::Handle<v8::Object> target); FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type); - v8::Handle<v8::Value> JpegEncode(); + v8::Handle<v8::Value> JpegEncodeSync(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); - static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif
pkrumins/node-jpeg
4020d264f7495af27c2c37cf914c23a67c698b33
Jpeg class is now async!
diff --git a/examples/jpeg-example-async.js b/examples/jpeg-example-async.js new file mode 100644 index 0000000..477feb8 --- /dev/null +++ b/examples/jpeg-example-async.js @@ -0,0 +1,14 @@ +var fs = require('fs'); +var sys = require('sys'); +var Jpeg = require('../jpeg').Jpeg; +var Buffer = require('buffer').Buffer; + +// the rgba-terminal.dat file is 1152000 bytes long. +var rgba = new Buffer(1152000); +rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); + +var jpeg = new Jpeg(rgba, 720, 400, 'rgba'); +jpeg.encode(function (image) { + fs.writeFileSync('./jpeg-async.jpeg', image, 'binary'); +}) + diff --git a/examples/jpeg-example.js b/examples/jpeg-example.js index f1fa266..3deae6f 100644 --- a/examples/jpeg-example.js +++ b/examples/jpeg-example.js @@ -1,14 +1,14 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; // the rgba-terminal.dat file is 1152000 bytes long. var rgba = new Buffer(1152000); rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); var jpeg = new Jpeg(rgba, 720, 400, 'rgba'); -var jpeg_img = jpeg.encode(); +var jpeg_img = jpeg.encodeSync(); fs.writeFileSync('./jpeg.jpeg', jpeg_img, 'binary'); diff --git a/examples/jpeg-example2-async.js b/examples/jpeg-example2-async.js new file mode 100644 index 0000000..12c67f6 --- /dev/null +++ b/examples/jpeg-example2-async.js @@ -0,0 +1,22 @@ +var fs = require('fs'); +var sys = require('sys'); +var Jpeg = require('../jpeg').Jpeg; +var Buffer = require('buffer').Buffer; + +var WIDTH = 400, HEIGHT = 300; + +var rgba = new Buffer(WIDTH*HEIGHT*3); + +for (var i=0; i<HEIGHT; i++) { + for (var j=0; j<WIDTH; j++) { + rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; + rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; + rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; + } +} + +var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 'rgb'); +var jpeg_img = jpeg.encode(); + +fs.writeFileSync('./jpeg-gradient.jpeg', jpeg_img, 'binary'); + diff --git a/examples/jpeg-example2.js b/examples/jpeg-example2.js index 12c67f6..3e78d1e 100644 --- a/examples/jpeg-example2.js +++ b/examples/jpeg-example2.js @@ -1,22 +1,22 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; var WIDTH = 400, HEIGHT = 300; var rgba = new Buffer(WIDTH*HEIGHT*3); for (var i=0; i<HEIGHT; i++) { for (var j=0; j<WIDTH; j++) { rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; } } var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 'rgb'); -var jpeg_img = jpeg.encode(); +var jpeg_img = jpeg.encodeSync(); fs.writeFileSync('./jpeg-gradient.jpeg', jpeg_img, 'binary'); diff --git a/src/common.cpp b/src/common.cpp index 490241c..968f4a1 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -1,67 +1,74 @@ #include <cstdlib> #include <cassert> #include "common.h" using namespace v8; +Handle<Value> +ErrorException(const char *msg) +{ + HandleScope scope; + return Exception::Error(String::New(msg)); +} + Handle<Value> VException(const char *msg) { HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); + return ThrowException(ErrorException(msg)); } bool str_eq(const char *s1, const char *s2) { return strcmp(s1, s2) == 0; } unsigned char * rgba_to_rgb(const unsigned char *rgba, int rgba_size) { assert(rgba_size%4==0); int rgb_size = rgba_size*3/4; unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*rgb_size); if (!rgb) return NULL; for (int i=0,j=0; i<rgba_size; i+=4,j+=3) { rgb[j] = rgba[i]; rgb[j+1] = rgba[i+1]; rgb[j+2] = rgba[i+2]; } return rgb; } unsigned char * bgra_to_rgb(const unsigned char *bgra, int bgra_size) { assert(bgra_size%4==0); int rgb_size = bgra_size*3/4; unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*rgb_size); if (!rgb) return NULL; for (int i=0,j=0; i<bgra_size; i+=4,j+=3) { rgb[j] = bgra[i+2]; rgb[j+1] = bgra[i+1]; rgb[j+2] = bgra[i]; } return rgb; } unsigned char * bgr_to_rgb(const unsigned char *bgr, int bgr_size) { assert(bgr_size%3==0); unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*bgr_size); if (!rgb) return NULL; for (int i=0; i<bgr_size; i+=3) { rgb[i] = bgr[i+2]; rgb[i+1] = bgr[i+1]; rgb[i+2] = bgr[i]; } return rgb; } diff --git a/src/common.h b/src/common.h index abbeb8c..d172fc6 100644 --- a/src/common.h +++ b/src/common.h @@ -1,30 +1,39 @@ #ifndef COMMON_H #define COMMON_H #include <node.h> #include <cstring> +v8::Handle<v8::Value> ErrorException(const char *msg); v8::Handle<v8::Value> VException(const char *msg); struct Point { int x, y; Point() {} Point(int xx, int yy) : x(xx), y(yy) {} }; struct Rect { int x, y, w, h; Rect() {} Rect(int xx, int yy, int ww, int hh) : x(xx), y(yy), w(ww), h(hh) {} bool isNull() { return x == 0 && y == 0 && w == 0 && h == 0; } }; bool str_eq(const char *s1, const char *s2); unsigned char *rgba_to_rgb(const unsigned char *rgba, int rgba_size); unsigned char *bgra_to_rgb(const unsigned char *rgba, int bgra_size); unsigned char *bgr_to_rgb(const unsigned char *rgb, int rgb_size); typedef enum { BUF_RGB, BUF_BGR, BUF_RGBA, BUF_BGRA } buffer_type; +struct encode_request { + v8::Persistent<v8::Function> callback; + void *jpeg_obj; + char *jpeg; + int jpeg_len; + char *error; +}; + #endif diff --git a/src/jpeg.cpp b/src/jpeg.cpp index 0bc58d6..d9ce62d 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,136 +1,230 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); - NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncodeAsync); + NODE_SET_PROTOTYPE_METHOD(t, "encodeSync", JpegEncodeSync); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, 60, bbuf_type) {} Handle<Value> -Jpeg::JpegEncode() +Jpeg::JpegEncodeSync() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } void Jpeg::SetQuality(int q) { jpeg_encoder.set_quality(q); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() < 3) return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 4) { if (!args[3]->IsString()) return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[3]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> -Jpeg::JpegEncode(const Arguments &args) +Jpeg::JpegEncodeSync(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); - return scope.Close(jpeg->JpegEncode()); + return scope.Close(jpeg->JpegEncodeSync()); } Handle<Value> Jpeg::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); jpeg->SetQuality(q); return Undefined(); } +int +Jpeg::EIO_JpegEncode(eio_req *req) +{ + encode_request *enc_req = (encode_request *)req->data; + Jpeg *jpeg = (Jpeg *)enc_req->jpeg_obj; + + try { + jpeg->jpeg_encoder.encode(); + enc_req->jpeg_len = jpeg->jpeg_encoder.get_jpeg_len(); + enc_req->jpeg = (char *)malloc(sizeof(*enc_req->jpeg)*enc_req->jpeg_len); + if (!enc_req->jpeg) { + enc_req->error = strdup("malloc in Jpeg::EIO_JpegEncode failed."); + return 0; + } + else { + memcpy(enc_req->jpeg, jpeg->jpeg_encoder.get_jpeg(), enc_req->jpeg_len); + } + } + catch (const char *err) { + enc_req->error = strdup(err); + } + + return 0; +} + +int +Jpeg::EIO_JpegEncodeAfter(eio_req *req) +{ + HandleScope scope; + + ev_unref(EV_DEFAULT_UC); + encode_request *enc_req = (encode_request *)req->data; + + Handle<Value> argv[2]; + + if (enc_req->error) { + argv[0] = Undefined(); + argv[1] = ErrorException(enc_req->error); + } + else { + argv[0] = Local<Value>::New(Encode(enc_req->jpeg, enc_req->jpeg_len, BINARY)); + argv[1] = Undefined(); + } + + TryCatch try_catch; // don't quite see the necessity of this + + enc_req->callback->Call(Context::GetCurrent()->Global(), 2, argv); + + if (try_catch.HasCaught()) + FatalException(try_catch); + + enc_req->callback.Dispose(); + free(enc_req->jpeg); + free(enc_req->error); + + ((Jpeg *)enc_req->jpeg_obj)->Unref(); + free(enc_req); + + return 0; +} + +Handle<Value> +Jpeg::JpegEncodeAsync(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - callback function."); + + if (!args[0]->IsFunction()) + return VException("First argument must be a function."); + + Local<Function> callback = Local<Function>::Cast(args[0]); + Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); + + encode_request *enc_req = (encode_request *)malloc(sizeof(*enc_req)); + if (!enc_req) + return VException("malloc in Jpeg::JpegEncodeAsync failed."); + + enc_req->callback = Persistent<Function>::New(callback); + enc_req->jpeg_obj = jpeg; + enc_req->jpeg = NULL; + enc_req->jpeg_len = 0; + enc_req->error = NULL; + + eio_custom(EIO_JpegEncode, EIO_PRI_DEFAULT, EIO_JpegEncodeAfter, enc_req); + + ev_ref(EV_DEFAULT_UC); + jpeg->Ref(); + + return Undefined(); +} + diff --git a/src/jpeg.h b/src/jpeg.h index 474962f..e734c18 100644 --- a/src/jpeg.h +++ b/src/jpeg.h @@ -1,24 +1,27 @@ #ifndef JPEG_H #define JPEG_H #include <node.h> #include <node_buffer.h> #include "jpeg_encoder.h" class Jpeg : public node::ObjectWrap { JpegEncoder jpeg_encoder; + static int EIO_JpegEncode(eio_req *req); + static int EIO_JpegEncodeAfter(eio_req *req); public: static void Initialize(v8::Handle<v8::Object> target); Jpeg(node::Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type); - v8::Handle<v8::Value> JpegEncode(); + v8::Handle<v8::Value> JpegEncodeSync(); void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); - static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncodeSync(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncodeAsync(const v8::Arguments &args); static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif diff --git a/wscript b/wscript index 368fc3c..154af3f 100644 --- a/wscript +++ b/wscript @@ -1,29 +1,30 @@ import Options from os import unlink, symlink, popen from os.path import exists srcdir = "." blddir = "build" VERSION = "0.0.1" def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.target = "jpeg" obj.source = "src/common.cpp src/jpeg_encoder.cpp src/jpeg.cpp src/fixed_jpeg_stack.cpp src/dynamic_jpeg_stack.cpp src/module.cpp" obj.uselib = "JPEG" + obj.cxxflags = ["-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE"] def shutdown(): if Options.commands['clean']: if exists('jpeg.node'): unlink('jpeg.node') else: if exists('build/default/jpeg.node') and not exists('jpeg.node'): symlink('build/default/jpeg.node', 'jpeg.node')
pkrumins/node-jpeg
30fce44baa2be517eb9d758883adcbc51739fa69
move to switch/case. forgot to free converted BUF_BGR data pointer
diff --git a/src/jpeg_encoder.cpp b/src/jpeg_encoder.cpp index f01155f..97aa948 100644 --- a/src/jpeg_encoder.cpp +++ b/src/jpeg_encoder.cpp @@ -1,200 +1,204 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } #if JPEG_LIB_VERSION < 80 // copied over from latest libjpeg #define OUTPUT_BUF_SIZE 4096 typedef struct { struct jpeg_destination_mgr pub; /* public fields */ unsigned char ** outbuffer; /* target buffer */ unsigned long * outsize; unsigned char * newbuffer; /* newly allocated buffer */ JOCTET * buffer; /* start of buffer */ size_t bufsize; } my_mem_destination_mgr; typedef my_mem_destination_mgr * my_mem_dest_ptr; void init_mem_destination (j_compress_ptr cinfo) { /* no work necessary here */ } boolean empty_mem_output_buffer (j_compress_ptr cinfo) { size_t nextsize; JOCTET * nextbuffer; my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; /* Try to allocate new buffer with double size */ nextsize = dest->bufsize * 2; nextbuffer = (JOCTET *)malloc(nextsize); if (nextbuffer == NULL) throw "malloc failed in empty_mem_output_buffer"; memcpy(nextbuffer, dest->buffer, dest->bufsize); if (dest->newbuffer != NULL) free(dest->newbuffer); dest->newbuffer = nextbuffer; dest->pub.next_output_byte = nextbuffer + dest->bufsize; dest->pub.free_in_buffer = dest->bufsize; dest->buffer = nextbuffer; dest->bufsize = nextsize; return TRUE; } void term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; } void jpeg_mem_dest (j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize) { my_mem_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_mem_dest. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_mem_destination_mgr)); } dest = (my_mem_dest_ptr) cinfo->dest; dest->pub.init_destination = init_mem_destination; dest->pub.empty_output_buffer = empty_mem_output_buffer; dest->pub.term_destination = term_mem_destination; dest->outbuffer = outbuffer; dest->outsize = outsize; dest->newbuffer = NULL; if (*outbuffer == NULL || *outsize == 0) { /* Allocate initial buffer */ dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE); if (dest->newbuffer == NULL) throw "out of memory in jpeg_mem_dest (copied implementation)"; *outsize = OUTPUT_BUF_SIZE; } dest->pub.next_output_byte = dest->buffer = *outbuffer; dest->pub.free_in_buffer = dest->bufsize = *outsize; } #endif void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; - if (buf_type == BUF_RGBA) { + switch (buf_type) { + case BUF_RGBA: rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; - } - else if (buf_type == BUF_BGRA) { + break; + + case BUF_BGRA: rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; + break; - } - else if (buf_type == BUF_BGR) { + case BUF_BGR: rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; - } - else if (buf_type == BUF_RGB) { + break; + + case BUF_RGB: rgb_data = data; - } - else { - throw "Unknown buf_type"; + break; + + default: + throw "Unexpected buf_type in JpegEncoder::encode"; } JSAMPROW row_pointer; int start = 0; if (!offset.isNull()) { start = offset.y*width*3 + offset.x*3; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); - if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) + if (buf_type == BUF_BGR || buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } void JpegEncoder::set_quality(int q) { quality = q; } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; }
pkrumins/node-jpeg
448bea70f96eb07c61bdbc3d64e0e562d607ff84
improve the same code madness as in dynamic jpeg stack
diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index afbcc10..9380b50 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,230 +1,246 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; - if (buf_type == BUF_RGB) { + switch (buf_type) { + case BUF_RGB: for (int i = 0; i < h; i++) { - for (int j = 0; j < 3*w; j+=3) { - data[start + i*width*3 + j] = data_buf[i*w*3 + j]; - data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; - data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j + 2]; + unsigned char *datap = &data[start + i*width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *data_buf++; + *datap++ = *data_buf++; + *datap++ = *data_buf++; } } - } - else if (buf_type == BUF_BGR) { + break; + + case BUF_BGR: for (int i = 0; i < h; i++) { - for (int j = 0; j < 3*w; j+=3) { - data[start + i*width*3 + j] = data_buf[i*w*3 + j + 2]; - data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; - data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j]; + unsigned char *datap = &data[start + i*width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *(data_buf+2); + *datap++ = *(data_buf+1); + *datap++ = *data_buf; + data_buf+=3; } } - } - else if (buf_type == BUF_RGBA) { + break; + + case BUF_RGBA: for (int i = 0; i < h; i++) { - for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { - data[start + i*width*3 + j] = data_buf[i*w*4 + k]; - data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; - data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k + 2]; + unsigned char *datap = &data[start + i*width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *data_buf++; + *datap++ = *data_buf++; + *datap++ = *data_buf++; + data_buf++; } } - } - else if (buf_type == BUF_BGRA) { + break; + + case BUF_BGRA: for (int i = 0; i < h; i++) { - for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { - data[start + i*width*3 + j] = data_buf[i*w*4 + k + 2]; - data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; - data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k]; + unsigned char *datap = &data[start + i*width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *(data_buf+2); + *datap++ = *(data_buf+1); + *datap++ = *data_buf; + data_buf += 4; } } + break; + + default: + throw "Unexpected buf_type in FixedJpegStack::Push"; } } + void FixedJpegStack::SetQuality(int q) { quality = q; } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() < 2) return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); buffer_type buf_type = BUF_RGB; if (args.Length() == 3) { if (!args[2]->IsString()) return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[2]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> FixedJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); }
pkrumins/node-jpeg
1aef540cc4594e9bf0f00ae9f2754e303cdc9969
make this a switch/case instead of if/else if/else if/..., too
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index fe7feaa..d2416f7 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,360 +1,376 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { UpdateOptimalDimension(x, y, w, h); int start = y*bg_width*3 + x*3; - if (buf_type == BUF_RGB) { + switch (buf_type) { + case BUF_RGB: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; } } - } - else if (buf_type == BUF_BGR) { + break; + + case BUF_BGR: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf+=3; } } - } - else if (buf_type == BUF_RGBA) { + break; + + case BUF_RGBA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *data_buf++; *datap++ = *data_buf++; *datap++ = *data_buf++; data_buf++; } } - } - else if (buf_type == BUF_BGRA) { + break; + + case BUF_BGRA: for (int i = 0; i < h; i++) { unsigned char *datap = &data[start + i*bg_width*3]; for (int j = 0; j < w; j++) { *datap++ = *(data_buf+2); *datap++ = *(data_buf+1); *datap++ = *data_buf; data_buf += 4; } } + break; + + default: + throw "Unexpected buf_type in DynamicJpegStack::Push"; } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } - if (buf_type == BUF_RGB) { + switch (buf_type) { + case BUF_RGB: data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); - } - else if (buf_type == BUF_BGR) { + break; + + case BUF_BGR: data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; - } - else if (buf_type == BUF_RGBA) { + break; + + case BUF_RGBA: data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; - } - else if (buf_type == BUF_BGRA) { + break; + + case BUF_BGRA: data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; + break; + + default: + throw "Unexpected buf_type in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); }
pkrumins/node-jpeg
97d96d3004319321958668881abcbc5e10a52bcd
improved this crayzy code
diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index e5042f4..fe7feaa 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,353 +1,360 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { UpdateOptimalDimension(x, y, w, h); int start = y*bg_width*3 + x*3; if (buf_type == BUF_RGB) { for (int i = 0; i < h; i++) { - for (int j = 0; j < 3*w; j+=3) { - data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; - data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; - data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; + unsigned char *datap = &data[start + i*bg_width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *data_buf++; + *datap++ = *data_buf++; + *datap++ = *data_buf++; } } } else if (buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { - for (int j = 0; j < 3*w; j+=3) { - data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j + 2]; - data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; - data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j]; + unsigned char *datap = &data[start + i*bg_width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *(data_buf+2); + *datap++ = *(data_buf+1); + *datap++ = *data_buf; + data_buf+=3; } } } else if (buf_type == BUF_RGBA) { for (int i = 0; i < h; i++) { - for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { - data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; - data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; - data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; + unsigned char *datap = &data[start + i*bg_width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *data_buf++; + *datap++ = *data_buf++; + *datap++ = *data_buf++; + data_buf++; } } } else if (buf_type == BUF_BGRA) { for (int i = 0; i < h; i++) { - for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { - data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k + 2]; - data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; - data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k]; + unsigned char *datap = &data[start + i*bg_width*3]; + for (int j = 0; j < w; j++) { + *datap++ = *(data_buf+2); + *datap++ = *(data_buf+1); + *datap++ = *data_buf; + data_buf += 4; } } } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } if (buf_type == BUF_RGB) { data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); } else if (buf_type == BUF_BGR) { data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } else if (buf_type == BUF_RGBA) { data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } else if (buf_type == BUF_BGRA) { data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::SetQuality(int q) { quality = q; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() > 1) return VException("One argument max - buffer type."); buffer_type buf_type = BUF_RGB; if (args.Length() == 1) { if (!args[0]->IsString()) return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); String::AsciiValue bt(args[0]->ToString()); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) { return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); } if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); } DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } Handle<Value> DynamicJpegStack::SetQuality(const Arguments &args) { HandleScope scope; if (args.Length() != 1) return VException("One argument required - quality"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality"); int q = args[0]->Int32Value(); if (q < 0) return VException("Quality must be greater or equal to 0."); if (q > 100) return VException("Quality must be less than or equal to 100."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->SetQuality(q); return Undefined(); }
pkrumins/node-jpeg
9407c4bdfca40eccbb1dce5c83ce49e43d4980b0
quality is no longer an argument to ctor. fix examples. 'rgb' is now the default buffer input type.
diff --git a/examples/dynamic-jpeg-stack.js b/examples/dynamic-jpeg-stack.js index ed78100..d100188 100644 --- a/examples/dynamic-jpeg-stack.js +++ b/examples/dynamic-jpeg-stack.js @@ -1,35 +1,35 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; // -------- var terminal = fs.readFileSync('./rgba-terminal.dat'); -var jpegStack = new JpegLib.DynamicJpegStack(60, 'rgba'); +var jpegStack = new JpegLib.DynamicJpegStack('rgba'); jpegStack.setBackground(terminal, 720, 400); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); var rgba = fs.readFileSync('./push-data/' + file, 'binary'); var buf = new Buffer(rgba.length); buf.write(rgba, 'binary'); jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); }); fs.writeFileSync('dynamic.jpg', jpegStack.encode(), 'binary'); var dims = jpegStack.dimensions(); sys.puts("x: " + dims.x + ", y: " + dims.y + ", w: " + dims.width + ", h: " + dims.height); diff --git a/examples/fixed-jpeg-stack.js b/examples/fixed-jpeg-stack.js index 3546814..b156313 100644 --- a/examples/fixed-jpeg-stack.js +++ b/examples/fixed-jpeg-stack.js @@ -1,27 +1,27 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; -var jpegStack = new JpegLib.FixedJpegStack(720, 400, 60, 'rgba'); +var jpegStack = new JpegLib.FixedJpegStack(720, 400, 'rgba'); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); var rgba = fs.readFileSync('./push-data/' + file, 'binary'); var buf = new Buffer(rgba.length); buf.write(rgba, 'binary'); jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); }); fs.writeFileSync('fixed.jpg', jpegStack.encode(), 'binary'); diff --git a/examples/jpeg-example.js b/examples/jpeg-example.js index 3e8dded..f1fa266 100644 --- a/examples/jpeg-example.js +++ b/examples/jpeg-example.js @@ -1,14 +1,14 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; // the rgba-terminal.dat file is 1152000 bytes long. var rgba = new Buffer(1152000); rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); -var jpeg = new Jpeg(rgba, 720, 400, 70, 'rgba'); +var jpeg = new Jpeg(rgba, 720, 400, 'rgba'); var jpeg_img = jpeg.encode(); fs.writeFileSync('./jpeg.jpeg', jpeg_img, 'binary'); diff --git a/examples/jpeg-example2.js b/examples/jpeg-example2.js index 65031a7..12c67f6 100644 --- a/examples/jpeg-example2.js +++ b/examples/jpeg-example2.js @@ -1,22 +1,22 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; var WIDTH = 400, HEIGHT = 300; var rgba = new Buffer(WIDTH*HEIGHT*3); for (var i=0; i<HEIGHT; i++) { for (var j=0; j<WIDTH; j++) { rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; } } -var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 50, 'rgb'); +var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 'rgb'); var jpeg_img = jpeg.encode(); fs.writeFileSync('./jpeg-gradient.jpeg', jpeg_img, 'binary'); diff --git a/src/dynamic_jpeg_stack.cpp b/src/dynamic_jpeg_stack.cpp index cf45c13..e5042f4 100644 --- a/src/dynamic_jpeg_stack.cpp +++ b/src/dynamic_jpeg_stack.cpp @@ -1,323 +1,353 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); + NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } -DynamicJpegStack::DynamicJpegStack(int qquality, buffer_type bbuf_type) : - quality(qquality), buf_type(bbuf_type), +DynamicJpegStack::DynamicJpegStack(buffer_type bbuf_type) : + quality(60), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} DynamicJpegStack::~DynamicJpegStack() { free(data); } void DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; - } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { UpdateOptimalDimension(x, y, w, h); int start = y*bg_width*3 + x*3; if (buf_type == BUF_RGB) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } else if (buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j + 2]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j]; } } } else if (buf_type == BUF_RGBA) { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } else if (buf_type == BUF_BGRA) { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k + 2]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k]; } } } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) { free(data); data = NULL; } if (buf_type == BUF_RGB) { data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); } else if (buf_type == BUF_BGR) { data = bgr_to_rgb(data_buf, w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } else if (buf_type == BUF_RGBA) { data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } else if (buf_type == BUF_BGRA) { data = bgra_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } +void +DynamicJpegStack::SetQuality(int q) +{ + quality = q; +} + void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; - if (args.Length() != 2) - return VException("Two arguments required - quality and buffer type"); - if (!args[0]->IsInt32()) - return VException("First argument must be integer quality."); - if (!args[1]->IsString()) - return VException("Second argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); - - int quality = args[0]->Int32Value(); - String::AsciiValue bt(args[1]->ToString()); - - if (quality < 0 || quality > 100) - return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) - return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); - - buffer_type buf_type; - if (str_eq(*bt, "rgb")) - buf_type = BUF_RGB; - else if (str_eq(*bt, "bgr")) - buf_type = BUF_BGR; - else if (str_eq(*bt, "rgba")) - buf_type = BUF_RGBA; - else if (str_eq(*bt, "bgra")) - buf_type = BUF_BGRA; - else - return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); - - DynamicJpegStack *jpeg = new DynamicJpegStack(quality, buf_type); + if (args.Length() > 1) + return VException("One argument max - buffer type."); + + buffer_type buf_type = BUF_RGB; + if (args.Length() == 1) { + if (!args[0]->IsString()) + return VException("First argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); + + String::AsciiValue bt(args[0]->ToString()); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || + str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) + { + return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); + } + + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "bgr")) + buf_type = BUF_BGR; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else if (str_eq(*bt, "bgra")) + buf_type = BUF_BGRA; + else + return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); + } + + DynamicJpegStack *jpeg = new DynamicJpegStack(buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } +Handle<Value> +DynamicJpegStack::SetQuality(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - quality"); + + if (!args[0]->IsInt32()) + return VException("First argument must be integer quality"); + + int q = args[0]->Int32Value(); + + if (q < 0) + return VException("Quality must be greater or equal to 0."); + if (q > 100) + return VException("Quality must be less than or equal to 100."); + + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + jpeg->SetQuality(q); + + return Undefined(); +} + diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h index b595e12..55f2248 100644 --- a/src/dynamic_jpeg_stack.h +++ b/src/dynamic_jpeg_stack.h @@ -1,44 +1,46 @@ #ifndef DYNAMIC_JPEG_H #define DYNAMIC_JPEG_H #include <node.h> #include <node_buffer.h> #include <vector> #include <utility> #include "common.h" #include "jpeg_encoder.h" class DynamicJpegStack : public node::ObjectWrap { int quality; buffer_type buf_type; unsigned char *data; int bg_width, bg_height; // background width and height after setBackground Rect dyn_rect; // rect of dynamic push area (updated after each push) void UpdateOptimalDimension(int x, int y, int w, int h); public: - DynamicJpegStack(int qquality, buffer_type bbuf_type); + DynamicJpegStack(buffer_type bbuf_type); ~DynamicJpegStack(); v8::Handle<v8::Value> JpegEncode(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetBackground(unsigned char *data_buf, int w, int h); + void SetQuality(int q); v8::Handle<v8::Value> Dimensions(); void Reset(); static void Initialize(v8::Handle<v8::Object> target); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); + static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); static v8::Handle<v8::Value> Reset(const v8::Arguments &args); }; #endif diff --git a/src/fixed_jpeg_stack.cpp b/src/fixed_jpeg_stack.cpp index 070525c..afbcc10 100644 --- a/src/fixed_jpeg_stack.cpp +++ b/src/fixed_jpeg_stack.cpp @@ -1,197 +1,230 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); + NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } -FixedJpegStack::FixedJpegStack(int wwidth, int hheight, int qquality, buffer_type bbuf_type) : - width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type) +FixedJpegStack::FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type) : + width(wwidth), height(hheight), quality(60), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; if (buf_type == BUF_RGB) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*width*3 + j] = data_buf[i*w*3 + j]; data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } else if (buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*width*3 + j] = data_buf[i*w*3 + j + 2]; data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j]; } } } else if (buf_type == BUF_RGBA) { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*width*3 + j] = data_buf[i*w*4 + k]; data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } else if (buf_type == BUF_BGRA) { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*width*3 + j] = data_buf[i*w*4 + k + 2]; data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k]; } } } } +void +FixedJpegStack::SetQuality(int q) +{ + quality = q; +} + Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; - if (args.Length() != 4) - return VException("Four arguments required - width, height, quality and buffer type"); + if (args.Length() < 2) + return VException("At least two arguments required - width, height, [and buffer type]"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); - if (!args[2]->IsInt32()) - return VException("Third argument must be integer quality."); - if (!args[3]->IsString()) - return VException("Fourth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); - int quality = args[2]->Int32Value(); - String::AsciiValue bt(args[3]->ToString()); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); - if (quality < 0 || quality > 100) - return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) - return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); - - buffer_type buf_type; - if (str_eq(*bt, "rgb")) - buf_type = BUF_RGB; - else if (str_eq(*bt, "bgr")) - buf_type = BUF_BGR; - else if (str_eq(*bt, "rgba")) - buf_type = BUF_RGBA; - else if (str_eq(*bt, "bgra")) - buf_type = BUF_BGRA; - else - return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); + + buffer_type buf_type = BUF_RGB; + if (args.Length() == 3) { + if (!args[2]->IsString()) + return VException("Third argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); + + String::AsciiValue bt(args[2]->ToString()); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || + str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) + { + return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); + } + + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "bgr")) + buf_type = BUF_BGR; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else if (str_eq(*bt, "bgra")) + buf_type = BUF_BGRA; + else + return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); + } try { - FixedJpegStack *jpeg = new FixedJpegStack(w, h, quality, buf_type); + FixedJpegStack *jpeg = new FixedJpegStack(w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } +Handle<Value> +FixedJpegStack::SetQuality(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - quality"); + + if (!args[0]->IsInt32()) + return VException("First argument must be integer quality"); + + int q = args[0]->Int32Value(); + + if (q < 0) + return VException("Quality must be greater or equal to 0."); + if (q > 100) + return VException("Quality must be less than or equal to 100."); + + FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); + jpeg->SetQuality(q); + + return Undefined(); +} + diff --git a/src/fixed_jpeg_stack.h b/src/fixed_jpeg_stack.h index b1bb518..54783ef 100644 --- a/src/fixed_jpeg_stack.h +++ b/src/fixed_jpeg_stack.h @@ -1,28 +1,30 @@ #ifndef STACKED_JPEG_H #define STACKED_JPEG_H #include <node.h> #include <node_buffer.h> #include "common.h" #include "jpeg_encoder.h" class FixedJpegStack : public node::ObjectWrap { int width, height, quality; buffer_type buf_type; unsigned char *data; public: static void Initialize(v8::Handle<v8::Object> target); - FixedJpegStack(int wwidth, int hheight, int qquality, buffer_type bbuf_type); + FixedJpegStack(int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncode(); void Push(unsigned char *data_buf, int x, int y, int w, int h); + void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); + static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif diff --git a/src/jpeg.cpp b/src/jpeg.cpp index ceaa241..0bc58d6 100644 --- a/src/jpeg.cpp +++ b/src/jpeg.cpp @@ -1,102 +1,136 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + NODE_SET_PROTOTYPE_METHOD(t, "setQuality", SetQuality); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } -Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : - jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, qquality, bbuf_type) {} +Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type) : + jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, 60, bbuf_type) {} Handle<Value> Jpeg::JpegEncode() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } +void +Jpeg::SetQuality(int q) +{ + jpeg_encoder.set_quality(q); +} + Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; - if (args.Length() != 5) - return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); + if (args.Length() < 3) + return VException("At least three arguments required - buffer, width, height, [and buffer type]"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); - if (!args[3]->IsInt32()) - return VException("Fourth argument must be integer quality."); - if (!args[4]->IsString()) - return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); - int quality = args[3]->Int32Value(); - String::AsciiValue bt(args[4]->ToString()); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); - if (quality < 0 || quality > 100) - return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) - return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); - - buffer_type buf_type; - if (str_eq(*bt, "rgb")) - buf_type = BUF_RGB; - else if (str_eq(*bt, "bgr")) - buf_type = BUF_BGR; - else if (str_eq(*bt, "rgba")) - buf_type = BUF_RGBA; - else if (str_eq(*bt, "bgra")) - buf_type = BUF_BGRA; - else - return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); + + buffer_type buf_type = BUF_RGB; + if (args.Length() == 4) { + if (!args[3]->IsString()) + return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); + + String::AsciiValue bt(args[3]->ToString()); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || + str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) + { + return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); + } + + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "bgr")) + buf_type = BUF_BGR; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else if (str_eq(*bt, "bgra")) + buf_type = BUF_BGRA; + else + return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); + } Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); - Jpeg *jpeg = new Jpeg(data_buf, w, h, quality, buf_type); + Jpeg *jpeg = new Jpeg(data_buf, w, h, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncode(const Arguments &args) { HandleScope scope; + Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); - return jpeg->JpegEncode(); + return scope.Close(jpeg->JpegEncode()); +} + +Handle<Value> +Jpeg::SetQuality(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 1) + return VException("One argument required - quality"); + + if (!args[0]->IsInt32()) + return VException("First argument must be integer quality"); + + int q = args[0]->Int32Value(); + + if (q < 0) + return VException("Quality must be greater or equal to 0."); + if (q > 100) + return VException("Quality must be less than or equal to 100."); + + Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); + jpeg->SetQuality(q); + + return Undefined(); } diff --git a/src/jpeg.h b/src/jpeg.h index 532ea6c..474962f 100644 --- a/src/jpeg.h +++ b/src/jpeg.h @@ -1,22 +1,24 @@ #ifndef JPEG_H #define JPEG_H #include <node.h> #include <node_buffer.h> #include "jpeg_encoder.h" class Jpeg : public node::ObjectWrap { JpegEncoder jpeg_encoder; public: static void Initialize(v8::Handle<v8::Object> target); - Jpeg(node::Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type); + Jpeg(node::Buffer *ddata, int wwidth, int hheight, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncode(); + void SetQuality(int q); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); + static v8::Handle<v8::Value> SetQuality(const v8::Arguments &args); }; #endif diff --git a/src/jpeg_encoder.cpp b/src/jpeg_encoder.cpp index bcb6b1d..f01155f 100644 --- a/src/jpeg_encoder.cpp +++ b/src/jpeg_encoder.cpp @@ -1,194 +1,200 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } #if JPEG_LIB_VERSION < 80 // copied over from latest libjpeg #define OUTPUT_BUF_SIZE 4096 typedef struct { struct jpeg_destination_mgr pub; /* public fields */ unsigned char ** outbuffer; /* target buffer */ unsigned long * outsize; unsigned char * newbuffer; /* newly allocated buffer */ JOCTET * buffer; /* start of buffer */ size_t bufsize; } my_mem_destination_mgr; typedef my_mem_destination_mgr * my_mem_dest_ptr; void init_mem_destination (j_compress_ptr cinfo) { /* no work necessary here */ } boolean empty_mem_output_buffer (j_compress_ptr cinfo) { size_t nextsize; JOCTET * nextbuffer; my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; /* Try to allocate new buffer with double size */ nextsize = dest->bufsize * 2; nextbuffer = (JOCTET *)malloc(nextsize); if (nextbuffer == NULL) throw "malloc failed in empty_mem_output_buffer"; memcpy(nextbuffer, dest->buffer, dest->bufsize); if (dest->newbuffer != NULL) free(dest->newbuffer); dest->newbuffer = nextbuffer; dest->pub.next_output_byte = nextbuffer + dest->bufsize; dest->pub.free_in_buffer = dest->bufsize; dest->buffer = nextbuffer; dest->bufsize = nextsize; return TRUE; } void term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; } void jpeg_mem_dest (j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize) { my_mem_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_mem_dest. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_mem_destination_mgr)); } dest = (my_mem_dest_ptr) cinfo->dest; dest->pub.init_destination = init_mem_destination; dest->pub.empty_output_buffer = empty_mem_output_buffer; dest->pub.term_destination = term_mem_destination; dest->outbuffer = outbuffer; dest->outsize = outsize; dest->newbuffer = NULL; if (*outbuffer == NULL || *outsize == 0) { /* Allocate initial buffer */ dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE); if (dest->newbuffer == NULL) throw "out of memory in jpeg_mem_dest (copied implementation)"; *outsize = OUTPUT_BUF_SIZE; } dest->pub.next_output_byte = dest->buffer = *outbuffer; dest->pub.free_in_buffer = dest->bufsize = *outsize; } #endif void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type == BUF_RGBA) { rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; } else if (buf_type == BUF_BGRA) { rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; } else if (buf_type == BUF_BGR) { rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; } else if (buf_type == BUF_RGB) { rgb_data = data; } else { throw "Unknown buf_type"; } JSAMPROW row_pointer; int start = 0; if (!offset.isNull()) { start = offset.y*width*3 + offset.x*3; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } +void +JpegEncoder::set_quality(int q) +{ + quality = q; +} + const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; } diff --git a/src/jpeg_encoder.h b/src/jpeg_encoder.h index b8dfbaf..7d7528c 100644 --- a/src/jpeg_encoder.h +++ b/src/jpeg_encoder.h @@ -1,32 +1,33 @@ #ifndef JPEG_ENCODER_H #define JPEG_ENCODER_H #include <cstdio> #include <cstdlib> #include <jpeglib.h> #include "common.h" class JpegEncoder { int width, height, quality; buffer_type buf_type; unsigned char *data; unsigned char *jpeg; long unsigned int jpeg_len; Rect offset; public: JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type); ~JpegEncoder(); void encode(); + void set_quality(int qquality); const unsigned char *get_jpeg() const; unsigned int get_jpeg_len() const; void setRect(const Rect &r); }; #endif
pkrumins/node-jpeg
7248a56b665e7b96063f0ff7c2778f51dc1b3c71
rename .cc -> .cpp
diff --git a/package.json b/package.json index 3d70dd8..2c61ebd 100644 --- a/package.json +++ b/package.json @@ -1,42 +1,43 @@ { "name": "jpeg", "version": "1.0.0", "main": "jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "maintainers": [ { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" } ], "licenses": [ { "type": "MIT" } ], "repositories": [ { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" } ], "directories": { - "examples": "examples" + "examples": "examples", + "src": "src" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-waf configure build" } } diff --git a/src/common.cc b/src/common.cpp similarity index 100% rename from src/common.cc rename to src/common.cpp diff --git a/src/dynamic_jpeg_stack.cc b/src/dynamic_jpeg_stack.cpp similarity index 100% rename from src/dynamic_jpeg_stack.cc rename to src/dynamic_jpeg_stack.cpp diff --git a/src/fixed_jpeg_stack.cc b/src/fixed_jpeg_stack.cpp similarity index 100% rename from src/fixed_jpeg_stack.cc rename to src/fixed_jpeg_stack.cpp diff --git a/src/jpeg.cc b/src/jpeg.cpp similarity index 100% rename from src/jpeg.cc rename to src/jpeg.cpp diff --git a/src/jpeg_encoder.cc b/src/jpeg_encoder.cpp similarity index 100% rename from src/jpeg_encoder.cc rename to src/jpeg_encoder.cpp diff --git a/src/module.cc b/src/module.cpp similarity index 100% rename from src/module.cc rename to src/module.cpp diff --git a/wscript b/wscript index 2ecb0fe..368fc3c 100644 --- a/wscript +++ b/wscript @@ -1,29 +1,29 @@ import Options from os import unlink, symlink, popen from os.path import exists srcdir = "." blddir = "build" VERSION = "0.0.1" def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.target = "jpeg" - obj.source = "src/common.cc src/jpeg_encoder.cc src/jpeg.cc src/fixed_jpeg_stack.cc src/dynamic_jpeg_stack.cc src/module.cc" + obj.source = "src/common.cpp src/jpeg_encoder.cpp src/jpeg.cpp src/fixed_jpeg_stack.cpp src/dynamic_jpeg_stack.cpp src/module.cpp" obj.uselib = "JPEG" def shutdown(): if Options.commands['clean']: if exists('jpeg.node'): unlink('jpeg.node') else: if exists('build/default/jpeg.node') and not exists('jpeg.node'): symlink('build/default/jpeg.node', 'jpeg.node')
pkrumins/node-jpeg
01fa97a074c93bc459905279a3d633c7e05c46fb
could sometimes double-free. push now works with all buffer types (rgb, bgr, rgba, bgra)
diff --git a/src/dynamic_jpeg_stack.cc b/src/dynamic_jpeg_stack.cc index 03c9cc7..cf45c13 100644 --- a/src/dynamic_jpeg_stack.cc +++ b/src/dynamic_jpeg_stack.cc @@ -1,289 +1,323 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(int qquality, buffer_type bbuf_type) : quality(qquality), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} +DynamicJpegStack::~DynamicJpegStack() +{ + free(data); +} + void DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { UpdateOptimalDimension(x, y, w, h); int start = y*bg_width*3 + x*3; - if (buf_type == BUF_RGB || buf_type == BUF_BGR) { + if (buf_type == BUF_RGB) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } - else { + else if (buf_type == BUF_BGR) { + for (int i = 0; i < h; i++) { + for (int j = 0; j < 3*w; j+=3) { + data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j + 2]; + data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; + data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j]; + } + } + } + else if (buf_type == BUF_RGBA) { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } + else if (buf_type == BUF_BGRA) { + for (int i = 0; i < h; i++) { + for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { + data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k + 2]; + data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; + data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k]; + } + } + } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { - if (data) free(data); + if (data) { + free(data); + data = NULL; + } if (buf_type == BUF_RGB) { data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); } - else { + else if (buf_type == BUF_BGR) { + data = bgr_to_rgb(data_buf, w*h*3); + if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; + } + else if (buf_type == BUF_RGBA) { data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } + else if (buf_type == BUF_BGRA) { + data = bgra_to_rgb(data_buf, w*h*4); + if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; + } bg_width = w; bg_height = h; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() != 2) return VException("Two arguments required - quality and buffer type"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality."); if (!args[1]->IsString()) return VException("Second argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int quality = args[0]->Int32Value(); String::AsciiValue bt(args[1]->ToString()); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); DynamicJpegStack *jpeg = new DynamicJpegStack(quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h index a94d529..b595e12 100644 --- a/src/dynamic_jpeg_stack.h +++ b/src/dynamic_jpeg_stack.h @@ -1,43 +1,44 @@ #ifndef DYNAMIC_JPEG_H #define DYNAMIC_JPEG_H #include <node.h> #include <node_buffer.h> #include <vector> #include <utility> #include "common.h" #include "jpeg_encoder.h" class DynamicJpegStack : public node::ObjectWrap { int quality; buffer_type buf_type; unsigned char *data; int bg_width, bg_height; // background width and height after setBackground Rect dyn_rect; // rect of dynamic push area (updated after each push) void UpdateOptimalDimension(int x, int y, int w, int h); public: DynamicJpegStack(int qquality, buffer_type bbuf_type); + ~DynamicJpegStack(); v8::Handle<v8::Value> JpegEncode(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetBackground(unsigned char *data_buf, int w, int h); v8::Handle<v8::Value> Dimensions(); void Reset(); static void Initialize(v8::Handle<v8::Object> target); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); static v8::Handle<v8::Value> Reset(const v8::Arguments &args); }; #endif diff --git a/src/fixed_jpeg_stack.cc b/src/fixed_jpeg_stack.cc index 202f4f5..070525c 100644 --- a/src/fixed_jpeg_stack.cc +++ b/src/fixed_jpeg_stack.cc @@ -1,179 +1,197 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, int qquality, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; - if (buf_type == BUF_RGB || buf_type == BUF_BGR) { + if (buf_type == BUF_RGB) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*width*3 + j] = data_buf[i*w*3 + j]; data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } - else { + else if (buf_type == BUF_BGR) { + for (int i = 0; i < h; i++) { + for (int j = 0; j < 3*w; j+=3) { + data[start + i*width*3 + j] = data_buf[i*w*3 + j + 2]; + data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; + data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j]; + } + } + } + else if (buf_type == BUF_RGBA) { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*width*3 + j] = data_buf[i*w*4 + k]; data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } + else if (buf_type == BUF_BGRA) { + for (int i = 0; i < h; i++) { + for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { + data[start + i*width*3 + j] = data_buf[i*w*4 + k + 2]; + data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; + data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k]; + } + } + } } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() != 4) return VException("Four arguments required - width, height, quality and buffer type"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); if (!args[2]->IsInt32()) return VException("Third argument must be integer quality."); if (!args[3]->IsString()) return VException("Fourth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); int quality = args[2]->Int32Value(); String::AsciiValue bt(args[3]->ToString()); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "bgr")) buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else if (str_eq(*bt, "bgra")) buf_type = BUF_BGRA; else return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); }
pkrumins/node-jpeg
f0ced113539c05458914c8aa6aba769f3ccf782c
recognize 'bgr' and 'bgra' arguments.
diff --git a/src/dynamic_jpeg_stack.cc b/src/dynamic_jpeg_stack.cc index 4c0412a..03c9cc7 100644 --- a/src/dynamic_jpeg_stack.cc +++ b/src/dynamic_jpeg_stack.cc @@ -1,285 +1,289 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(int qquality, buffer_type bbuf_type) : quality(qquality), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} void DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { UpdateOptimalDimension(x, y, w, h); int start = y*bg_width*3 + x*3; if (buf_type == BUF_RGB || buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } else { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) free(data); if (buf_type == BUF_RGB) { data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); } else { data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() != 2) return VException("Two arguments required - quality and buffer type"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality."); if (!args[1]->IsString()) - return VException("Second argument must be a string. Either 'rgb' or 'rgba'."); + return VException("Second argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int quality = args[0]->Int32Value(); String::AsciiValue bt(args[1]->ToString()); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) - return VException("Buffer type must be either 'rgb' or 'rgba'."); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) + return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; + else if (str_eq(*bt, "bgr")) + buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; + else if (str_eq(*bt, "bgra")) + buf_type = BUF_BGRA; else - return VException("Buffer type wasn't 'rgb' or 'rgba'"); + return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); DynamicJpegStack *jpeg = new DynamicJpegStack(quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } diff --git a/src/fixed_jpeg_stack.cc b/src/fixed_jpeg_stack.cc index 8657cad..202f4f5 100644 --- a/src/fixed_jpeg_stack.cc +++ b/src/fixed_jpeg_stack.cc @@ -1,175 +1,179 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "fixed_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void FixedJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); } FixedJpegStack::FixedJpegStack(int wwidth, int hheight, int qquality, buffer_type bbuf_type) : width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type) { data = (unsigned char *)calloc(width*height*3, sizeof(*data)); if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; } Handle<Value> FixedJpegStack::JpegEncode() { HandleScope scope; try { JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { int start = y*width*3 + x*3; if (buf_type == BUF_RGB || buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*width*3 + j] = data_buf[i*w*3 + j]; data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } else { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*width*3 + j] = data_buf[i*w*4 + k]; data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } } Handle<Value> FixedJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() != 4) return VException("Four arguments required - width, height, quality and buffer type"); if (!args[0]->IsInt32()) return VException("First argument must be integer width."); if (!args[1]->IsInt32()) return VException("Second argument must be integer height."); if (!args[2]->IsInt32()) return VException("Third argument must be integer quality."); if (!args[3]->IsString()) - return VException("Fourth argument must be a string. Either 'rgb' or 'rgba'."); + return VException("Fourth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int w = args[0]->Int32Value(); int h = args[1]->Int32Value(); int quality = args[2]->Int32Value(); String::AsciiValue bt(args[3]->ToString()); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) - return VException("Buffer type must be either 'rgb' or 'rgba'."); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) + return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; + else if (str_eq(*bt, "bgr")) + buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; + else if (str_eq(*bt, "bgra")) + buf_type = BUF_BGRA; else - return VException("Buffer type wasn't 'rgb' or 'rgba'"); + return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); try { FixedJpegStack *jpeg = new FixedJpegStack(w, h, quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } catch (const char *err) { return VException(err); } } Handle<Value> FixedJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> FixedJpegStack::Push(const Arguments &args) { HandleScope scope; if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->width) return VException("Coordinate x exceeds FixedJpegStack's dimensions."); if (y >= jpeg->height) return VException("Coordinate y exceeds FixedJpegStack's dimensions."); if (x+w > jpeg->width) return VException("Pushed fragment exceeds FixedJpegStack's width."); if (y+h > jpeg->height) return VException("Pushed fragment exceeds FixedJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } diff --git a/src/jpeg.cc b/src/jpeg.cc index 9e1e3c8..ceaa241 100644 --- a/src/jpeg.cc +++ b/src/jpeg.cc @@ -1,98 +1,102 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, qquality, bbuf_type) {} Handle<Value> Jpeg::JpegEncode() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer quality."); if (!args[4]->IsString()) - return VException("Fifth argument must be a string. Either 'rgb' or 'rgba'."); + return VException("Fifth argument must be a string. Either 'rgb', 'bgr', 'rgba' or 'bgra'."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); int quality = args[3]->Int32Value(); String::AsciiValue bt(args[4]->ToString()); if (w < 0) return VException("Width can't be negative."); if (h < 0) return VException("Height can't be negative."); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) - return VException("Buffer type must be either 'rgb' or 'rgba'."); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "bgr") || str_eq(*bt, "rgba") || str_eq(*bt, "bgra"))) + return VException("Buffer type must be 'rgb', 'bgr', 'rgba' or 'bgra'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; + else if (str_eq(*bt, "bgr")) + buf_type = BUF_BGR; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; + else if (str_eq(*bt, "bgra")) + buf_type = BUF_BGRA; else - return VException("Buffer type wasn't 'rgb' or 'rgba'"); + return VException("Buffer type wasn't 'rgb', 'bgr', 'rgba' or 'bgra'."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> Jpeg::JpegEncode(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return jpeg->JpegEncode(); }
pkrumins/node-jpeg
6e71c07fb7c4deac0f8d3ad9522ec7f91f8afe81
make encoder work with older libjpegs, such as libjpeg-turbo
diff --git a/src/jpeg_encoder.cc b/src/jpeg_encoder.cc index 733829c..bcb6b1d 100644 --- a/src/jpeg_encoder.cc +++ b/src/jpeg_encoder.cc @@ -1,96 +1,194 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } +#if JPEG_LIB_VERSION < 80 +// copied over from latest libjpeg + +#define OUTPUT_BUF_SIZE 4096 + +typedef struct { + struct jpeg_destination_mgr pub; /* public fields */ + + unsigned char ** outbuffer; /* target buffer */ + unsigned long * outsize; + unsigned char * newbuffer; /* newly allocated buffer */ + JOCTET * buffer; /* start of buffer */ + size_t bufsize; +} my_mem_destination_mgr; + +typedef my_mem_destination_mgr * my_mem_dest_ptr; + +void +init_mem_destination (j_compress_ptr cinfo) +{ + /* no work necessary here */ +} + +boolean +empty_mem_output_buffer (j_compress_ptr cinfo) +{ + size_t nextsize; + JOCTET * nextbuffer; + my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; + + /* Try to allocate new buffer with double size */ + nextsize = dest->bufsize * 2; + nextbuffer = (JOCTET *)malloc(nextsize); + + if (nextbuffer == NULL) + throw "malloc failed in empty_mem_output_buffer"; + + memcpy(nextbuffer, dest->buffer, dest->bufsize); + + if (dest->newbuffer != NULL) + free(dest->newbuffer); + + dest->newbuffer = nextbuffer; + + dest->pub.next_output_byte = nextbuffer + dest->bufsize; + dest->pub.free_in_buffer = dest->bufsize; + + dest->buffer = nextbuffer; + dest->bufsize = nextsize; + + return TRUE; +} + +void +term_mem_destination (j_compress_ptr cinfo) +{ + my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; + + *dest->outbuffer = dest->buffer; + *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; +} + +void +jpeg_mem_dest (j_compress_ptr cinfo, + unsigned char ** outbuffer, unsigned long * outsize) +{ + my_mem_dest_ptr dest; + + /* The destination object is made permanent so that multiple JPEG images + * can be written to the same buffer without re-executing jpeg_mem_dest. + */ + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + sizeof(my_mem_destination_mgr)); + } + + dest = (my_mem_dest_ptr) cinfo->dest; + dest->pub.init_destination = init_mem_destination; + dest->pub.empty_output_buffer = empty_mem_output_buffer; + dest->pub.term_destination = term_mem_destination; + dest->outbuffer = outbuffer; + dest->outsize = outsize; + dest->newbuffer = NULL; + + if (*outbuffer == NULL || *outsize == 0) { + /* Allocate initial buffer */ + dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE); + if (dest->newbuffer == NULL) + throw "out of memory in jpeg_mem_dest (copied implementation)"; + *outsize = OUTPUT_BUF_SIZE; + } + + dest->pub.next_output_byte = dest->buffer = *outbuffer; + dest->pub.free_in_buffer = dest->bufsize = *outsize; +} +#endif + void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type == BUF_RGBA) { rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; } else if (buf_type == BUF_BGRA) { rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; } else if (buf_type == BUF_BGR) { rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; } else if (buf_type == BUF_RGB) { rgb_data = data; } else { throw "Unknown buf_type"; } JSAMPROW row_pointer; int start = 0; if (!offset.isNull()) { start = offset.y*width*3 + offset.x*3; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; }
pkrumins/node-jpeg
49cc12c4447fd7a37f1d6a279fa24e0c8aff7d10
output dims
diff --git a/examples/dynamic-jpeg-stack.js b/examples/dynamic-jpeg-stack.js index e46842f..ed78100 100644 --- a/examples/dynamic-jpeg-stack.js +++ b/examples/dynamic-jpeg-stack.js @@ -1,32 +1,35 @@ var JpegLib = require('jpeg'); var fs = require('fs'); var sys = require('sys'); var Buffer = require('buffer').Buffer; // -------- var terminal = fs.readFileSync('./rgba-terminal.dat'); var jpegStack = new JpegLib.DynamicJpegStack(60, 'rgba'); jpegStack.setBackground(terminal, 720, 400); function rectDim(fileName) { var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); var dim = [m[1], m[2], m[3], m[4]].map(function (n) { return parseInt(n, 10); }); return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } } var files = fs.readdirSync('./push-data'); files.forEach(function(file) { var dim = rectDim(file); var rgba = fs.readFileSync('./push-data/' + file, 'binary'); var buf = new Buffer(rgba.length); buf.write(rgba, 'binary'); jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); }); fs.writeFileSync('dynamic.jpg', jpegStack.encode(), 'binary'); +var dims = jpegStack.dimensions(); + +sys.puts("x: " + dims.x + ", y: " + dims.y + ", w: " + dims.width + ", h: " + dims.height);
pkrumins/node-jpeg
cd3d203b4a90d3584496041adc8f1a142151b13a
remove debug statement
diff --git a/src/dynamic_jpeg_stack.cc b/src/dynamic_jpeg_stack.cc index 5c07a81..4c0412a 100644 --- a/src/dynamic_jpeg_stack.cc +++ b/src/dynamic_jpeg_stack.cc @@ -1,287 +1,285 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(int qquality, buffer_type bbuf_type) : quality(qquality), buf_type(bbuf_type), dyn_rect(-1, -1, 0, 0), bg_width(0), bg_height(0), data(NULL) {} void DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { if (dyn_rect.x == -1 || x < dyn_rect.x) dyn_rect.x = x; if (dyn_rect.y == -1 || y < dyn_rect.y) dyn_rect.y = y; if (dyn_rect.w == 0) dyn_rect.w = w; if (dyn_rect.h == 0) dyn_rect.h = h; int ww = w - (dyn_rect.w - (x - dyn_rect.x)); if (ww > 0) dyn_rect.w += ww; int hh = h - (dyn_rect.h - (y - dyn_rect.y)); if (hh > 0) dyn_rect.h += hh; } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; - printf("%d %d\n", dyn_rect.w, dyn_rect.h); - try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { UpdateOptimalDimension(x, y, w, h); int start = y*bg_width*3 + x*3; if (buf_type == BUF_RGB || buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } else { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) free(data); if (buf_type == BUF_RGB) { data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); } else { data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } void DynamicJpegStack::Reset() { dyn_rect = Rect(-1, -1, 0, 0); } Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() != 2) return VException("Two arguments required - quality and buffer type"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality."); if (!args[1]->IsString()) return VException("Second argument must be a string. Either 'rgb' or 'rgba'."); int quality = args[0]->Int32Value(); String::AsciiValue bt(args[1]->ToString()); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) return VException("Buffer type must be either 'rgb' or 'rgba'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else return VException("Buffer type wasn't 'rgb' or 'rgba'"); DynamicJpegStack *jpeg = new DynamicJpegStack(quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } Handle<Value> DynamicJpegStack::Reset(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); jpeg->Reset(); return Undefined(); } Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); }
pkrumins/node-jpeg
d5693fc78af1571faf8dea07e4587c1726398ee5
optimal dimension now gets computed on the fly. added .reset method to reset optimal dimension
diff --git a/src/dynamic_jpeg_stack.cc b/src/dynamic_jpeg_stack.cc index 8f02748..5c07a81 100644 --- a/src/dynamic_jpeg_stack.cc +++ b/src/dynamic_jpeg_stack.cc @@ -1,271 +1,287 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "dynamic_jpeg_stack.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); NODE_SET_PROTOTYPE_METHOD(t, "push", Push); + NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset); NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); } DynamicJpegStack::DynamicJpegStack(int qquality, buffer_type bbuf_type) : quality(qquality), buf_type(bbuf_type), - bg_width(0), bg_height(0), dyn_width(0), dyn_height(0), offset(0, 0), data(NULL) {} + dyn_rect(-1, -1, 0, 0), + bg_width(0), bg_height(0), data(NULL) {} -std::pair<Point, Point> -DynamicJpegStack::OptimalDimension() +void +DynamicJpegStack::UpdateOptimalDimension(int x, int y, int w, int h) { - Point top(-1, -1), bottom(-1, -1); - for (RectVector::iterator it = updates.begin(); it != updates.end(); ++it) { - Rect &r = *it; - if (top.x == -1 || r.x < top.x) - top.x = r.x; - if (top.y == -1 || r.y < top.y) - top.y = r.y; - if (bottom.x == -1 || r.x + r.w > bottom.x) - bottom.x = r.x + r.w; - if (bottom.y == -1 || r.y + r.h > bottom.y) - bottom.y = r.y + r.h; - } + if (dyn_rect.x == -1 || x < dyn_rect.x) + dyn_rect.x = x; + if (dyn_rect.y == -1 || y < dyn_rect.y) + dyn_rect.y = y; + + if (dyn_rect.w == 0) + dyn_rect.w = w; + if (dyn_rect.h == 0) + dyn_rect.h = h; + + int ww = w - (dyn_rect.w - (x - dyn_rect.x)); + if (ww > 0) + dyn_rect.w += ww; + + int hh = h - (dyn_rect.h - (y - dyn_rect.y)); + if (hh > 0) + dyn_rect.h += hh; - return std::make_pair(top, bottom); } Handle<Value> DynamicJpegStack::JpegEncode() { HandleScope scope; - // TODO: this can be computed on the fly as we push() to stack - std::pair<Point, Point> optimal = OptimalDimension(); - Point top = optimal.first, bot = optimal.second; - - offset = top; - dyn_width = bot.x - top.x; - dyn_height = bot.y - top.y; + printf("%d %d\n", dyn_rect.w, dyn_rect.h); try { JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); - jpeg_encoder.setRect(Rect(offset.x, offset.y, dyn_width, dyn_height)); + jpeg_encoder.setRect(Rect(dyn_rect.x, dyn_rect.y, dyn_rect.w, dyn_rect.h)); jpeg_encoder.encode(); return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } catch (const char *err) { return VException(err); } } void DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) { - int start = y*bg_width*3 + x*3; + UpdateOptimalDimension(x, y, w, h); - updates.push_back(Rect(x, y, w, h)); + int start = y*bg_width*3 + x*3; if (buf_type == BUF_RGB || buf_type == BUF_BGR) { for (int i = 0; i < h; i++) { for (int j = 0; j < 3*w; j+=3) { data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; } } } else { for (int i = 0; i < h; i++) { for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; } } } } void DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) { if (data) free(data); if (buf_type == BUF_RGB) { data = (unsigned char *)malloc(sizeof(*data)*w*h*3); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; memcpy(data, data_buf, w*h*3); } else { data = rgba_to_rgb(data_buf, w*h*4); if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; } bg_width = w; bg_height = h; } +void +DynamicJpegStack::Reset() +{ + dyn_rect = Rect(-1, -1, 0, 0); +} + Handle<Value> DynamicJpegStack::Dimensions() { HandleScope scope; Local<Object> dim = Object::New(); - dim->Set(String::NewSymbol("x"), Integer::New(offset.x)); - dim->Set(String::NewSymbol("y"), Integer::New(offset.y)); - dim->Set(String::NewSymbol("width"), Integer::New(dyn_width)); - dim->Set(String::NewSymbol("height"), Integer::New(dyn_height)); + dim->Set(String::NewSymbol("x"), Integer::New(dyn_rect.x)); + dim->Set(String::NewSymbol("y"), Integer::New(dyn_rect.y)); + dim->Set(String::NewSymbol("width"), Integer::New(dyn_rect.w)); + dim->Set(String::NewSymbol("height"), Integer::New(dyn_rect.h)); return scope.Close(dim); } Handle<Value> DynamicJpegStack::New(const Arguments &args) { HandleScope scope; if (args.Length() != 2) return VException("Two arguments required - quality and buffer type"); if (!args[0]->IsInt32()) return VException("First argument must be integer quality."); if (!args[1]->IsString()) return VException("Second argument must be a string. Either 'rgb' or 'rgba'."); int quality = args[0]->Int32Value(); String::AsciiValue bt(args[1]->ToString()); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) return VException("Buffer type must be either 'rgb' or 'rgba'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else return VException("Buffer type wasn't 'rgb' or 'rgba'"); DynamicJpegStack *jpeg = new DynamicJpegStack(quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> DynamicJpegStack::JpegEncode(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return jpeg->JpegEncode(); } Handle<Value> DynamicJpegStack::Push(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - buffer, x, y, width, height."); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer x."); if (!args[2]->IsInt32()) return VException("Third argument must be integer y."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer w."); if (!args[4]->IsInt32()) return VException("Fifth argument must be integer h."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); if (!jpeg->data) return VException("No background has been set, use setBackground or setSolidBackground to set."); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int x = args[1]->Int32Value(); int y = args[2]->Int32Value(); int w = args[3]->Int32Value(); int h = args[4]->Int32Value(); if (x < 0) return VException("Coordinate x smaller than 0."); if (y < 0) return VException("Coordinate y smaller than 0."); if (w < 0) return VException("Width smaller than 0."); if (h < 0) return VException("Height smaller than 0."); if (x >= jpeg->bg_width) return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); if (y >= jpeg->bg_height) return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); if (x+w > jpeg->bg_width) return VException("Pushed fragment exceeds DynamicJpegStack's width."); if (y+h > jpeg->bg_height) return VException("Pushed fragment exceeds DynamicJpegStack's height."); jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); return Undefined(); } Handle<Value> DynamicJpegStack::SetBackground(const Arguments &args) { HandleScope scope; if (args.Length() != 3) return VException("Four arguments required - buffer, width, height"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); if (w < 0) return VException("Coordinate x smaller than 0."); if (h < 0) return VException("Coordinate y smaller than 0."); try { jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); } catch (const char *err) { return VException(err); } return Undefined(); } +Handle<Value> +DynamicJpegStack::Reset(const Arguments &args) +{ + HandleScope scope; + + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + jpeg->Reset(); + return Undefined(); +} + Handle<Value> DynamicJpegStack::Dimensions(const Arguments &args) { HandleScope scope; DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); return scope.Close(jpeg->Dimensions()); } diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h index 57f8d6a..a94d529 100644 --- a/src/dynamic_jpeg_stack.h +++ b/src/dynamic_jpeg_stack.h @@ -1,45 +1,43 @@ #ifndef DYNAMIC_JPEG_H #define DYNAMIC_JPEG_H #include <node.h> #include <node_buffer.h> #include <vector> #include <utility> #include "common.h" #include "jpeg_encoder.h" class DynamicJpegStack : public node::ObjectWrap { - int bg_width, bg_height; - int dyn_width, dyn_height; - Point offset; - int quality; buffer_type buf_type; unsigned char *data; - typedef std::vector<Rect> RectVector; - RectVector updates; + int bg_width, bg_height; // background width and height after setBackground + Rect dyn_rect; // rect of dynamic push area (updated after each push) - std::pair<Point, Point> OptimalDimension(); + void UpdateOptimalDimension(int x, int y, int w, int h); public: DynamicJpegStack(int qquality, buffer_type bbuf_type); v8::Handle<v8::Value> JpegEncode(); void Push(unsigned char *data_buf, int x, int y, int w, int h); void SetBackground(unsigned char *data_buf, int w, int h); v8::Handle<v8::Value> Dimensions(); + void Reset(); static void Initialize(v8::Handle<v8::Object> target); static v8::Handle<v8::Value> New(const v8::Arguments &args); static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); static v8::Handle<v8::Value> Push(const v8::Arguments &args); static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); + static v8::Handle<v8::Value> Reset(const v8::Arguments &args); }; #endif
pkrumins/node-jpeg
5d581171f73e63484db5940b0aa5edd2c770f609
no need for repeated code, just set start correctly
diff --git a/src/jpeg_encoder.cc b/src/jpeg_encoder.cc index aad41b2..733829c 100644 --- a/src/jpeg_encoder.cc +++ b/src/jpeg_encoder.cc @@ -1,102 +1,96 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0), offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); if (offset.isNull()) { cinfo.image_width = width; cinfo.image_height = height; } else { cinfo.image_width = offset.w; cinfo.image_height = offset.h; } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type == BUF_RGBA) { rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; } else if (buf_type == BUF_BGRA) { rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; } else if (buf_type == BUF_BGR) { rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; } else if (buf_type == BUF_RGB) { rgb_data = data; } else { throw "Unknown buf_type"; } JSAMPROW row_pointer; - - if (offset.isNull()) { - while (cinfo.next_scanline < cinfo.image_height) { - row_pointer = &rgb_data[cinfo.next_scanline*3*width]; - jpeg_write_scanlines(&cinfo, &row_pointer, 1); - } + int start = 0; + if (!offset.isNull()) { + start = offset.y*width*3 + offset.x*3; } - else { - int start = offset.y*width*3 + offset.x*3; - while (cinfo.next_scanline < cinfo.image_height) { - row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; - jpeg_write_scanlines(&cinfo, &row_pointer, 1); - } + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; + jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } void JpegEncoder::setRect(const Rect &r) { offset = r; }
pkrumins/node-jpeg
baa4946d56214589a456a322eb1de75091ff8204
added dynamic jpeg stack example
diff --git a/examples/dynamic-jpeg-stack.js b/examples/dynamic-jpeg-stack.js new file mode 100644 index 0000000..e46842f --- /dev/null +++ b/examples/dynamic-jpeg-stack.js @@ -0,0 +1,32 @@ +var JpegLib = require('jpeg'); +var fs = require('fs'); +var sys = require('sys'); +var Buffer = require('buffer').Buffer; + +// -------- + +var terminal = fs.readFileSync('./rgba-terminal.dat'); + +var jpegStack = new JpegLib.DynamicJpegStack(60, 'rgba'); +jpegStack.setBackground(terminal, 720, 400); + +function rectDim(fileName) { + var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); + var dim = [m[1], m[2], m[3], m[4]].map(function (n) { + return parseInt(n, 10); + }); + return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } +} + +var files = fs.readdirSync('./push-data'); + +files.forEach(function(file) { + var dim = rectDim(file); + var rgba = fs.readFileSync('./push-data/' + file, 'binary'); + var buf = new Buffer(rgba.length); + buf.write(rgba, 'binary'); + jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); +}); + +fs.writeFileSync('dynamic.jpg', jpegStack.encode(), 'binary'); +
pkrumins/node-jpeg
c50cb32a6943cda78a0f4752ac084d09df10fa92
compile dynamic_jpeg_stack.cc
diff --git a/wscript b/wscript index 0fe0a33..2ecb0fe 100644 --- a/wscript +++ b/wscript @@ -1,29 +1,29 @@ import Options from os import unlink, symlink, popen from os.path import exists srcdir = "." blddir = "build" VERSION = "0.0.1" def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.target = "jpeg" - obj.source = "src/common.cc src/jpeg_encoder.cc src/jpeg.cc src/fixed_jpeg_stack.cc src/module.cc" + obj.source = "src/common.cc src/jpeg_encoder.cc src/jpeg.cc src/fixed_jpeg_stack.cc src/dynamic_jpeg_stack.cc src/module.cc" obj.uselib = "JPEG" def shutdown(): if Options.commands['clean']: if exists('jpeg.node'): unlink('jpeg.node') else: if exists('build/default/jpeg.node') and not exists('jpeg.node'): symlink('build/default/jpeg.node', 'jpeg.node')
pkrumins/node-jpeg
ccb381ac101ac3db983a58b7fecc114c7bf77415
export DynamicJpegStack to node
diff --git a/src/module.cc b/src/module.cc index d4ddb5f..593142d 100644 --- a/src/module.cc +++ b/src/module.cc @@ -1,15 +1,17 @@ #include <node.h> #include "jpeg.h" #include "fixed_jpeg_stack.h" +#include "dynamic_jpeg_stack.h" using namespace v8; extern "C" void init(Handle<Object> target) { HandleScope scope; Jpeg::Initialize(target); FixedJpegStack::Initialize(target); + DynamicJpegStack::Initialize(target); }
pkrumins/node-jpeg
7c94f02b5f99f00f20e18b585fce19ae6e90d7a7
added setRect to encode a subrect only (used in dynamic jpeg stack)
diff --git a/src/jpeg_encoder.cc b/src/jpeg_encoder.cc index 0a6c7e5..aad41b2 100644 --- a/src/jpeg_encoder.cc +++ b/src/jpeg_encoder.cc @@ -1,78 +1,102 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : data(ddata), width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type), - jpeg(NULL), jpeg_len(0) {} + jpeg(NULL), jpeg_len(0), + offset(0, 0, 0, 0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); - cinfo.image_width = width; - cinfo.image_height = height; + if (offset.isNull()) { + cinfo.image_width = width; + cinfo.image_height = height; + } + else { + cinfo.image_width = offset.w; + cinfo.image_height = offset.h; + } cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type == BUF_RGBA) { rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; } else if (buf_type == BUF_BGRA) { rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; } else if (buf_type == BUF_BGR) { rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; } else if (buf_type == BUF_RGB) { rgb_data = data; } else { throw "Unknown buf_type"; } JSAMPROW row_pointer; - while (cinfo.next_scanline < cinfo.image_height) { - row_pointer = &rgb_data[cinfo.next_scanline*3*width]; - jpeg_write_scanlines(&cinfo, &row_pointer, 1); + + if (offset.isNull()) { + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer = &rgb_data[cinfo.next_scanline*3*width]; + jpeg_write_scanlines(&cinfo, &row_pointer, 1); + } + } + else { + int start = offset.y*width*3 + offset.x*3; + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer = &rgb_data[start + cinfo.next_scanline*3*width]; + jpeg_write_scanlines(&cinfo, &row_pointer, 1); + } } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; } + +void +JpegEncoder::setRect(const Rect &r) +{ + offset = r; +} + diff --git a/src/jpeg_encoder.h b/src/jpeg_encoder.h index cd148fc..b8dfbaf 100644 --- a/src/jpeg_encoder.h +++ b/src/jpeg_encoder.h @@ -1,28 +1,32 @@ #ifndef JPEG_ENCODER_H #define JPEG_ENCODER_H #include <cstdio> #include <cstdlib> #include <jpeglib.h> #include "common.h" class JpegEncoder { int width, height, quality; buffer_type buf_type; unsigned char *data; unsigned char *jpeg; long unsigned int jpeg_len; + Rect offset; + public: JpegEncoder(unsigned char *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type); ~JpegEncoder(); void encode(); const unsigned char *get_jpeg() const; unsigned int get_jpeg_len() const; + + void setRect(const Rect &r); }; #endif
pkrumins/node-jpeg
23af6ee3efeedcd72da437b4ded2952b599ec20b
added Point and Rect classes
diff --git a/src/common.h b/src/common.h index 15168a2..abbeb8c 100644 --- a/src/common.h +++ b/src/common.h @@ -1,17 +1,30 @@ #ifndef COMMON_H #define COMMON_H #include <node.h> #include <cstring> v8::Handle<v8::Value> VException(const char *msg); +struct Point { + int x, y; + Point() {} + Point(int xx, int yy) : x(xx), y(yy) {} +}; + +struct Rect { + int x, y, w, h; + Rect() {} + Rect(int xx, int yy, int ww, int hh) : x(xx), y(yy), w(ww), h(hh) {} + bool isNull() { return x == 0 && y == 0 && w == 0 && h == 0; } +}; + bool str_eq(const char *s1, const char *s2); unsigned char *rgba_to_rgb(const unsigned char *rgba, int rgba_size); unsigned char *bgra_to_rgb(const unsigned char *rgba, int bgra_size); unsigned char *bgr_to_rgb(const unsigned char *rgb, int rgb_size); typedef enum { BUF_RGB, BUF_BGR, BUF_RGBA, BUF_BGRA } buffer_type; #endif
pkrumins/node-jpeg
7cb2e806dcd9aa2042729fd406972644bc0c9d25
added dynamic jpeg stack
diff --git a/src/dynamic_jpeg_stack.cc b/src/dynamic_jpeg_stack.cc new file mode 100644 index 0000000..8f02748 --- /dev/null +++ b/src/dynamic_jpeg_stack.cc @@ -0,0 +1,271 @@ +#include <node.h> +#include <node_buffer.h> +#include <jpeglib.h> +#include <cstdlib> +#include <cstring> + +#include "common.h" +#include "dynamic_jpeg_stack.h" +#include "jpeg_encoder.h" + +using namespace v8; +using namespace node; + +void +DynamicJpegStack::Initialize(v8::Handle<v8::Object> target) +{ + HandleScope scope; + + Local<FunctionTemplate> t = FunctionTemplate::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + NODE_SET_PROTOTYPE_METHOD(t, "push", Push); + NODE_SET_PROTOTYPE_METHOD(t, "setBackground", SetBackground); + NODE_SET_PROTOTYPE_METHOD(t, "dimensions", Dimensions); + target->Set(String::NewSymbol("DynamicJpegStack"), t->GetFunction()); +} + +DynamicJpegStack::DynamicJpegStack(int qquality, buffer_type bbuf_type) : + quality(qquality), buf_type(bbuf_type), + bg_width(0), bg_height(0), dyn_width(0), dyn_height(0), offset(0, 0), data(NULL) {} + +std::pair<Point, Point> +DynamicJpegStack::OptimalDimension() +{ + Point top(-1, -1), bottom(-1, -1); + for (RectVector::iterator it = updates.begin(); it != updates.end(); ++it) { + Rect &r = *it; + if (top.x == -1 || r.x < top.x) + top.x = r.x; + if (top.y == -1 || r.y < top.y) + top.y = r.y; + if (bottom.x == -1 || r.x + r.w > bottom.x) + bottom.x = r.x + r.w; + if (bottom.y == -1 || r.y + r.h > bottom.y) + bottom.y = r.y + r.h; + } + + return std::make_pair(top, bottom); +} + +Handle<Value> +DynamicJpegStack::JpegEncode() +{ + HandleScope scope; + + // TODO: this can be computed on the fly as we push() to stack + std::pair<Point, Point> optimal = OptimalDimension(); + Point top = optimal.first, bot = optimal.second; + + offset = top; + dyn_width = bot.x - top.x; + dyn_height = bot.y - top.y; + + try { + JpegEncoder jpeg_encoder(data, bg_width, bg_height, quality, BUF_RGB); + jpeg_encoder.setRect(Rect(offset.x, offset.y, dyn_width, dyn_height)); + jpeg_encoder.encode(); + return scope.Close( + Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) + ); + } + catch (const char *err) { + return VException(err); + } +} + +void +DynamicJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) +{ + int start = y*bg_width*3 + x*3; + + updates.push_back(Rect(x, y, w, h)); + + if (buf_type == BUF_RGB || buf_type == BUF_BGR) { + for (int i = 0; i < h; i++) { + for (int j = 0; j < 3*w; j+=3) { + data[start + i*bg_width*3 + j] = data_buf[i*w*3 + j]; + data[start + i*bg_width*3 + j + 1] = data_buf[i*w*3 + j + 1]; + data[start + i*bg_width*3 + j + 2] = data_buf[i*w*3 + j + 2]; + } + } + } + else { + for (int i = 0; i < h; i++) { + for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { + data[start + i*bg_width*3 + j] = data_buf[i*w*4 + k]; + data[start + i*bg_width*3 + j + 1] = data_buf[i*w*4 + k + 1]; + data[start + i*bg_width*3 + j + 2] = data_buf[i*w*4 + k + 2]; + } + } + } +} + +void +DynamicJpegStack::SetBackground(unsigned char *data_buf, int w, int h) +{ + if (data) free(data); + + if (buf_type == BUF_RGB) { + data = (unsigned char *)malloc(sizeof(*data)*w*h*3); + if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; + memcpy(data, data_buf, w*h*3); + } + else { + data = rgba_to_rgb(data_buf, w*h*4); + if (!data) throw "malloc failed in DynamicJpegStack::SetBackground"; + } + bg_width = w; + bg_height = h; +} + +Handle<Value> +DynamicJpegStack::Dimensions() +{ + HandleScope scope; + + Local<Object> dim = Object::New(); + dim->Set(String::NewSymbol("x"), Integer::New(offset.x)); + dim->Set(String::NewSymbol("y"), Integer::New(offset.y)); + dim->Set(String::NewSymbol("width"), Integer::New(dyn_width)); + dim->Set(String::NewSymbol("height"), Integer::New(dyn_height)); + + return scope.Close(dim); +} + +Handle<Value> +DynamicJpegStack::New(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 2) + return VException("Two arguments required - quality and buffer type"); + if (!args[0]->IsInt32()) + return VException("First argument must be integer quality."); + if (!args[1]->IsString()) + return VException("Second argument must be a string. Either 'rgb' or 'rgba'."); + + int quality = args[0]->Int32Value(); + String::AsciiValue bt(args[1]->ToString()); + + if (quality < 0 || quality > 100) + return VException("Quality must be between 0 and 100 (inclusive)."); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) + return VException("Buffer type must be either 'rgb' or 'rgba'."); + + buffer_type buf_type; + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else + return VException("Buffer type wasn't 'rgb' or 'rgba'"); + + DynamicJpegStack *jpeg = new DynamicJpegStack(quality, buf_type); + jpeg->Wrap(args.This()); + return args.This(); +} + +Handle<Value> +DynamicJpegStack::JpegEncode(const Arguments &args) +{ + HandleScope scope; + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + return jpeg->JpegEncode(); +} + +Handle<Value> +DynamicJpegStack::Push(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 5) + return VException("Five arguments required - buffer, x, y, width, height."); + + if (!Buffer::HasInstance(args[0])) + return VException("First argument must be Buffer."); + if (!args[1]->IsInt32()) + return VException("Second argument must be integer x."); + if (!args[2]->IsInt32()) + return VException("Third argument must be integer y."); + if (!args[3]->IsInt32()) + return VException("Fourth argument must be integer w."); + if (!args[4]->IsInt32()) + return VException("Fifth argument must be integer h."); + + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + + if (!jpeg->data) + return VException("No background has been set, use setBackground or setSolidBackground to set."); + + Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + int x = args[1]->Int32Value(); + int y = args[2]->Int32Value(); + int w = args[3]->Int32Value(); + int h = args[4]->Int32Value(); + + if (x < 0) + return VException("Coordinate x smaller than 0."); + if (y < 0) + return VException("Coordinate y smaller than 0."); + if (w < 0) + return VException("Width smaller than 0."); + if (h < 0) + return VException("Height smaller than 0."); + if (x >= jpeg->bg_width) + return VException("Coordinate x exceeds DynamicJpegStack's background dimensions."); + if (y >= jpeg->bg_height) + return VException("Coordinate y exceeds DynamicJpegStack's background dimensions."); + if (x+w > jpeg->bg_width) + return VException("Pushed fragment exceeds DynamicJpegStack's width."); + if (y+h > jpeg->bg_height) + return VException("Pushed fragment exceeds DynamicJpegStack's height."); + + jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); + + return Undefined(); +} + +Handle<Value> +DynamicJpegStack::SetBackground(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 3) + return VException("Four arguments required - buffer, width, height"); + if (!Buffer::HasInstance(args[0])) + return VException("First argument must be Buffer."); + if (!args[1]->IsInt32()) + return VException("Second argument must be integer width."); + if (!args[2]->IsInt32()) + return VException("Third argument must be integer height."); + + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + int w = args[1]->Int32Value(); + int h = args[2]->Int32Value(); + + if (w < 0) + return VException("Coordinate x smaller than 0."); + if (h < 0) + return VException("Coordinate y smaller than 0."); + + try { + jpeg->SetBackground((unsigned char *)data_buf->data(), w, h); + } + catch (const char *err) { + return VException(err); + } + + return Undefined(); +} + +Handle<Value> +DynamicJpegStack::Dimensions(const Arguments &args) +{ + HandleScope scope; + + DynamicJpegStack *jpeg = ObjectWrap::Unwrap<DynamicJpegStack>(args.This()); + return scope.Close(jpeg->Dimensions()); +} + diff --git a/src/dynamic_jpeg_stack.h b/src/dynamic_jpeg_stack.h new file mode 100644 index 0000000..57f8d6a --- /dev/null +++ b/src/dynamic_jpeg_stack.h @@ -0,0 +1,45 @@ +#ifndef DYNAMIC_JPEG_H +#define DYNAMIC_JPEG_H + +#include <node.h> +#include <node_buffer.h> + +#include <vector> +#include <utility> + +#include "common.h" +#include "jpeg_encoder.h" + +class DynamicJpegStack : public node::ObjectWrap { + int bg_width, bg_height; + int dyn_width, dyn_height; + Point offset; + + int quality; + buffer_type buf_type; + + unsigned char *data; + + typedef std::vector<Rect> RectVector; + RectVector updates; + + std::pair<Point, Point> OptimalDimension(); + +public: + DynamicJpegStack(int qquality, buffer_type bbuf_type); + + v8::Handle<v8::Value> JpegEncode(); + void Push(unsigned char *data_buf, int x, int y, int w, int h); + void SetBackground(unsigned char *data_buf, int w, int h); + v8::Handle<v8::Value> Dimensions(); + + static void Initialize(v8::Handle<v8::Object> target); + static v8::Handle<v8::Value> New(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); + static v8::Handle<v8::Value> Push(const v8::Arguments &args); + static v8::Handle<v8::Value> SetBackground(const v8::Arguments &args); + static v8::Handle<v8::Value> Dimensions(const v8::Arguments &args); +}; + +#endif +
pkrumins/node-jpeg
d0971cc950312cd24e87879c591af7f932a3de88
added FixedJpegStack
diff --git a/examples/fixed-jpeg-stack.js b/examples/fixed-jpeg-stack.js new file mode 100644 index 0000000..3546814 --- /dev/null +++ b/examples/fixed-jpeg-stack.js @@ -0,0 +1,27 @@ +var JpegLib = require('jpeg'); +var fs = require('fs'); +var sys = require('sys'); +var Buffer = require('buffer').Buffer; + +var jpegStack = new JpegLib.FixedJpegStack(720, 400, 60, 'rgba'); + +function rectDim(fileName) { + var m = fileName.match(/^\d+-rgba-(\d+)-(\d+)-(\d+)-(\d+).dat$/); + var dim = [m[1], m[2], m[3], m[4]].map(function (n) { + return parseInt(n, 10); + }); + return { x: dim[0], y: dim[1], w: dim[2], h: dim[3] } +} + +var files = fs.readdirSync('./push-data'); + +files.forEach(function(file) { + var dim = rectDim(file); + var rgba = fs.readFileSync('./push-data/' + file, 'binary'); + var buf = new Buffer(rgba.length); + buf.write(rgba, 'binary'); + jpegStack.push(buf, dim.x, dim.y, dim.w, dim.h); +}); + +fs.writeFileSync('fixed.jpg', jpegStack.encode(), 'binary'); + diff --git a/examples/push-data/01-rgba-80-389-16-7.dat b/examples/push-data/01-rgba-80-389-16-7.dat new file mode 100644 index 0000000..7d1a576 Binary files /dev/null and b/examples/push-data/01-rgba-80-389-16-7.dat differ diff --git a/examples/push-data/02-rgba-96-390-16-5.dat b/examples/push-data/02-rgba-96-390-16-5.dat new file mode 100644 index 0000000..12b163c Binary files /dev/null and b/examples/push-data/02-rgba-96-390-16-5.dat differ diff --git a/examples/push-data/03-rgba-80-397-32-2.dat b/examples/push-data/03-rgba-80-397-32-2.dat new file mode 100644 index 0000000..d13c329 Binary files /dev/null and b/examples/push-data/03-rgba-80-397-32-2.dat differ diff --git a/examples/push-data/04-rgba-96-386-16-10.dat b/examples/push-data/04-rgba-96-386-16-10.dat new file mode 100644 index 0000000..3528635 Binary files /dev/null and b/examples/push-data/04-rgba-96-386-16-10.dat differ diff --git a/examples/push-data/05-rgba-96-397-32-2.dat b/examples/push-data/05-rgba-96-397-32-2.dat new file mode 100644 index 0000000..f56b230 Binary files /dev/null and b/examples/push-data/05-rgba-96-397-32-2.dat differ diff --git a/examples/push-data/06-rgba-96-397-32-2.dat b/examples/push-data/06-rgba-96-397-32-2.dat new file mode 100644 index 0000000..dfdecd4 Binary files /dev/null and b/examples/push-data/06-rgba-96-397-32-2.dat differ diff --git a/examples/push-data/07-rgba-112-386-16-10.dat b/examples/push-data/07-rgba-112-386-16-10.dat new file mode 100644 index 0000000..4a9423a Binary files /dev/null and b/examples/push-data/07-rgba-112-386-16-10.dat differ diff --git a/examples/push-data/08-rgba-112-397-32-2.dat b/examples/push-data/08-rgba-112-397-32-2.dat new file mode 100644 index 0000000..1a4e9e2 Binary files /dev/null and b/examples/push-data/08-rgba-112-397-32-2.dat differ diff --git a/examples/push-data/09-rgba-112-389-32-7.dat b/examples/push-data/09-rgba-112-389-32-7.dat new file mode 100644 index 0000000..1419d7f Binary files /dev/null and b/examples/push-data/09-rgba-112-389-32-7.dat differ diff --git a/examples/push-data/10-rgba-112-397-32-2.dat b/examples/push-data/10-rgba-112-397-32-2.dat new file mode 100644 index 0000000..11780f6 Binary files /dev/null and b/examples/push-data/10-rgba-112-397-32-2.dat differ diff --git a/examples/push-data/11-rgba-128-386-16-10.dat b/examples/push-data/11-rgba-128-386-16-10.dat new file mode 100644 index 0000000..f53cf11 Binary files /dev/null and b/examples/push-data/11-rgba-128-386-16-10.dat differ diff --git a/examples/push-data/12-rgba-128-397-32-2.dat b/examples/push-data/12-rgba-128-397-32-2.dat new file mode 100644 index 0000000..6986c14 Binary files /dev/null and b/examples/push-data/12-rgba-128-397-32-2.dat differ diff --git a/examples/push-data/13-rgba-144-386-16-10.dat b/examples/push-data/13-rgba-144-386-16-10.dat new file mode 100644 index 0000000..3cf1703 Binary files /dev/null and b/examples/push-data/13-rgba-144-386-16-10.dat differ diff --git a/examples/push-data/14-rgba-144-397-32-2.dat b/examples/push-data/14-rgba-144-397-32-2.dat new file mode 100644 index 0000000..ce6a17f Binary files /dev/null and b/examples/push-data/14-rgba-144-397-32-2.dat differ diff --git a/examples/push-data/15-rgba-144-389-16-7.dat b/examples/push-data/15-rgba-144-389-16-7.dat new file mode 100644 index 0000000..5a494ba Binary files /dev/null and b/examples/push-data/15-rgba-144-389-16-7.dat differ diff --git a/examples/push-data/16-rgba-144-397-32-2.dat b/examples/push-data/16-rgba-144-397-32-2.dat new file mode 100644 index 0000000..6a10a3f Binary files /dev/null and b/examples/push-data/16-rgba-144-397-32-2.dat differ diff --git a/examples/push-data/17-rgba-160-393-16-6.dat b/examples/push-data/17-rgba-160-393-16-6.dat new file mode 100644 index 0000000..738ef6d Binary files /dev/null and b/examples/push-data/17-rgba-160-393-16-6.dat differ diff --git a/examples/push-data/18-rgba-176-397-16-2.dat b/examples/push-data/18-rgba-176-397-16-2.dat new file mode 100644 index 0000000..d7606cf Binary files /dev/null and b/examples/push-data/18-rgba-176-397-16-2.dat differ diff --git a/examples/push-data/19-rgba-160-397-32-2.dat b/examples/push-data/19-rgba-160-397-32-2.dat new file mode 100644 index 0000000..6d4bc26 Binary files /dev/null and b/examples/push-data/19-rgba-160-397-32-2.dat differ diff --git a/examples/push-data/20-rgba-176-386-16-10.dat b/examples/push-data/20-rgba-176-386-16-10.dat new file mode 100644 index 0000000..20193c0 Binary files /dev/null and b/examples/push-data/20-rgba-176-386-16-10.dat differ diff --git a/src/fixed_jpeg_stack.cc b/src/fixed_jpeg_stack.cc new file mode 100644 index 0000000..8657cad --- /dev/null +++ b/src/fixed_jpeg_stack.cc @@ -0,0 +1,175 @@ +#include <node.h> +#include <node_buffer.h> +#include <jpeglib.h> +#include <cstdlib> +#include <cstring> + +#include "common.h" +#include "fixed_jpeg_stack.h" +#include "jpeg_encoder.h" + +using namespace v8; +using namespace node; + +void +FixedJpegStack::Initialize(v8::Handle<v8::Object> target) +{ + HandleScope scope; + + Local<FunctionTemplate> t = FunctionTemplate::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + NODE_SET_PROTOTYPE_METHOD(t, "push", Push); + target->Set(String::NewSymbol("FixedJpegStack"), t->GetFunction()); +} + +FixedJpegStack::FixedJpegStack(int wwidth, int hheight, int qquality, buffer_type bbuf_type) : + width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type) +{ + data = (unsigned char *)calloc(width*height*3, sizeof(*data)); + if (!data) throw "calloc in FixedJpegStack::FixedJpegStack failed!"; +} + +Handle<Value> +FixedJpegStack::JpegEncode() +{ + HandleScope scope; + + try { + JpegEncoder jpeg_encoder(data, width, height, quality, BUF_RGB); + jpeg_encoder.encode(); + return scope.Close( + Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) + ); + } + catch (const char *err) { + return VException(err); + } +} + +void +FixedJpegStack::Push(unsigned char *data_buf, int x, int y, int w, int h) +{ + int start = y*width*3 + x*3; + + if (buf_type == BUF_RGB || buf_type == BUF_BGR) { + for (int i = 0; i < h; i++) { + for (int j = 0; j < 3*w; j+=3) { + data[start + i*width*3 + j] = data_buf[i*w*3 + j]; + data[start + i*width*3 + j + 1] = data_buf[i*w*3 + j + 1]; + data[start + i*width*3 + j + 2] = data_buf[i*w*3 + j + 2]; + } + } + } + else { + for (int i = 0; i < h; i++) { + for (int j = 0, k = 0; j < 3*w; j+=3, k+=4) { + data[start + i*width*3 + j] = data_buf[i*w*4 + k]; + data[start + i*width*3 + j + 1] = data_buf[i*w*4 + k + 1]; + data[start + i*width*3 + j + 2] = data_buf[i*w*4 + k + 2]; + } + } + } +} + +Handle<Value> +FixedJpegStack::New(const Arguments &args) +{ + HandleScope scope; + + if (args.Length() != 4) + return VException("Four arguments required - width, height, quality and buffer type"); + if (!args[0]->IsInt32()) + return VException("First argument must be integer width."); + if (!args[1]->IsInt32()) + return VException("Second argument must be integer height."); + if (!args[2]->IsInt32()) + return VException("Third argument must be integer quality."); + if (!args[3]->IsString()) + return VException("Fourth argument must be a string. Either 'rgb' or 'rgba'."); + + int w = args[0]->Int32Value(); + int h = args[1]->Int32Value(); + int quality = args[2]->Int32Value(); + String::AsciiValue bt(args[3]->ToString()); + + if (w < 0) + return VException("Width can't be negative."); + if (h < 0) + return VException("Height can't be negative."); + if (quality < 0 || quality > 100) + return VException("Quality must be between 0 and 100 (inclusive)."); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) + return VException("Buffer type must be either 'rgb' or 'rgba'."); + + buffer_type buf_type; + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else + return VException("Buffer type wasn't 'rgb' or 'rgba'"); + + try { + FixedJpegStack *jpeg = new FixedJpegStack(w, h, quality, buf_type); + jpeg->Wrap(args.This()); + return args.This(); + } + catch (const char *err) { + return VException(err); + } +} + +Handle<Value> +FixedJpegStack::JpegEncode(const Arguments &args) +{ + HandleScope scope; + FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); + return jpeg->JpegEncode(); +} + +Handle<Value> +FixedJpegStack::Push(const Arguments &args) +{ + HandleScope scope; + + if (!Buffer::HasInstance(args[0])) + return VException("First argument must be Buffer."); + if (!args[1]->IsInt32()) + return VException("Second argument must be integer x."); + if (!args[2]->IsInt32()) + return VException("Third argument must be integer y."); + if (!args[3]->IsInt32()) + return VException("Fourth argument must be integer w."); + if (!args[4]->IsInt32()) + return VException("Fifth argument must be integer h."); + + FixedJpegStack *jpeg = ObjectWrap::Unwrap<FixedJpegStack>(args.This()); + Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + int x = args[1]->Int32Value(); + int y = args[2]->Int32Value(); + int w = args[3]->Int32Value(); + int h = args[4]->Int32Value(); + + if (x < 0) + return VException("Coordinate x smaller than 0."); + if (y < 0) + return VException("Coordinate y smaller than 0."); + if (w < 0) + return VException("Width smaller than 0."); + if (h < 0) + return VException("Height smaller than 0."); + if (x >= jpeg->width) + return VException("Coordinate x exceeds FixedJpegStack's dimensions."); + if (y >= jpeg->height) + return VException("Coordinate y exceeds FixedJpegStack's dimensions."); + if (x+w > jpeg->width) + return VException("Pushed fragment exceeds FixedJpegStack's width."); + if (y+h > jpeg->height) + return VException("Pushed fragment exceeds FixedJpegStack's height."); + + jpeg->Push((unsigned char *)data_buf->data(), x, y, w, h); + + return Undefined(); +} + diff --git a/src/fixed_jpeg_stack.h b/src/fixed_jpeg_stack.h new file mode 100644 index 0000000..b1bb518 --- /dev/null +++ b/src/fixed_jpeg_stack.h @@ -0,0 +1,28 @@ +#ifndef STACKED_JPEG_H +#define STACKED_JPEG_H + +#include <node.h> +#include <node_buffer.h> + +#include "common.h" +#include "jpeg_encoder.h" + +class FixedJpegStack : public node::ObjectWrap { + int width, height, quality; + buffer_type buf_type; + + unsigned char *data; + +public: + static void Initialize(v8::Handle<v8::Object> target); + FixedJpegStack(int wwidth, int hheight, int qquality, buffer_type bbuf_type); + v8::Handle<v8::Value> JpegEncode(); + void Push(unsigned char *data_buf, int x, int y, int w, int h); + + static v8::Handle<v8::Value> New(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); + static v8::Handle<v8::Value> Push(const v8::Arguments &args); +}; + +#endif + diff --git a/src/module.cc b/src/module.cc index 0de1509..d4ddb5f 100644 --- a/src/module.cc +++ b/src/module.cc @@ -1,12 +1,15 @@ #include <node.h> + #include "jpeg.h" +#include "fixed_jpeg_stack.h" using namespace v8; extern "C" void init(Handle<Object> target) { HandleScope scope; Jpeg::Initialize(target); + FixedJpegStack::Initialize(target); } diff --git a/wscript b/wscript index e1cc611..0fe0a33 100644 --- a/wscript +++ b/wscript @@ -1,29 +1,29 @@ import Options from os import unlink, symlink, popen from os.path import exists srcdir = "." blddir = "build" VERSION = "0.0.1" def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.target = "jpeg" - obj.source = "src/common.cc src/jpeg_encoder.cc src/jpeg.cc src/module.cc" + obj.source = "src/common.cc src/jpeg_encoder.cc src/jpeg.cc src/fixed_jpeg_stack.cc src/module.cc" obj.uselib = "JPEG" def shutdown(): if Options.commands['clean']: if exists('jpeg.node'): unlink('jpeg.node') else: if exists('build/default/jpeg.node') and not exists('jpeg.node'): symlink('build/default/jpeg.node', 'jpeg.node')
pkrumins/node-jpeg
7e938fab97c3d0ed9294e7179808220b9870490f
i like this weird syntax better
diff --git a/src/jpeg_encoder.cc b/src/jpeg_encoder.cc index 7ff7d8f..0a6c7e5 100644 --- a/src/jpeg_encoder.cc +++ b/src/jpeg_encoder.cc @@ -1,77 +1,78 @@ #include "jpeg_encoder.h" JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, - int qquality, buffer_type bbuf_type) : + int qquality, buffer_type bbuf_type) + : data(ddata), width(wwidth), height(hheight), quality(qquality), buf_type(bbuf_type), jpeg(NULL), jpeg_len(0) {} JpegEncoder::~JpegEncoder() { free(jpeg); } void JpegEncoder::encode() { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type == BUF_RGBA) { rgb_data = rgba_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; } else if (buf_type == BUF_BGRA) { rgb_data = bgra_to_rgb(data, width*height*4); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; } else if (buf_type == BUF_BGR) { rgb_data = bgr_to_rgb(data, width*height*3); if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; } else if (buf_type == BUF_RGB) { rgb_data = data; } else { throw "Unknown buf_type"; } JSAMPROW row_pointer; while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) free(rgb_data); } const unsigned char * JpegEncoder::get_jpeg() const { return jpeg; } unsigned int JpegEncoder::get_jpeg_len() const { return jpeg_len; }
pkrumins/node-jpeg
f3d4a507b7ad2ac128d7e8ac0b10e29bd6700f40
added two checks for w<0 and h<0
diff --git a/src/jpeg.cc b/src/jpeg.cc index a30a754..9e1e3c8 100644 --- a/src/jpeg.cc +++ b/src/jpeg.cc @@ -1,94 +1,98 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> #include "common.h" #include "jpeg.h" #include "jpeg_encoder.h" using namespace v8; using namespace node; void Jpeg::Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, qquality, bbuf_type) {} Handle<Value> Jpeg::JpegEncode() { HandleScope scope; try { jpeg_encoder.encode(); } catch (const char *err) { return VException(err); } return scope.Close( Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) ); } Handle<Value> Jpeg::New(const Arguments &args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer quality."); if (!args[4]->IsString()) return VException("Fifth argument must be a string. Either 'rgb' or 'rgba'."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); int quality = args[3]->Int32Value(); String::AsciiValue bt(args[4]->ToString()); + if (w < 0) + return VException("Width can't be negative."); + if (h < 0) + return VException("Height can't be negative."); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) - return VException("Fifth argument must be either 'rgb' or 'rgba'."); + return VException("Buffer type must be either 'rgb' or 'rgba'."); buffer_type buf_type; if (str_eq(*bt, "rgb")) buf_type = BUF_RGB; else if (str_eq(*bt, "rgba")) buf_type = BUF_RGBA; else return VException("Buffer type wasn't 'rgb' or 'rgba'"); Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Jpeg *jpeg = new Jpeg(data_buf, w, h, quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } Handle<Value> -Jpeg::JpegEncode(const Arguments& args) +Jpeg::JpegEncode(const Arguments &args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return jpeg->JpegEncode(); }
pkrumins/node-jpeg
501af33427bc748b2b332234656f2bd3ab61efaa
move everything to src/ dir
diff --git a/common.cc b/src/common.cc similarity index 100% rename from common.cc rename to src/common.cc diff --git a/common.h b/src/common.h similarity index 100% rename from common.h rename to src/common.h diff --git a/jpeg.cc b/src/jpeg.cc similarity index 100% rename from jpeg.cc rename to src/jpeg.cc diff --git a/jpeg.h b/src/jpeg.h similarity index 100% rename from jpeg.h rename to src/jpeg.h diff --git a/jpeg_encoder.cc b/src/jpeg_encoder.cc similarity index 100% rename from jpeg_encoder.cc rename to src/jpeg_encoder.cc diff --git a/jpeg_encoder.h b/src/jpeg_encoder.h similarity index 100% rename from jpeg_encoder.h rename to src/jpeg_encoder.h diff --git a/module.cc b/src/module.cc similarity index 100% rename from module.cc rename to src/module.cc diff --git a/wscript b/wscript index 442bb85..e1cc611 100644 --- a/wscript +++ b/wscript @@ -1,29 +1,29 @@ import Options from os import unlink, symlink, popen from os.path import exists srcdir = "." blddir = "build" VERSION = "0.0.1" def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.target = "jpeg" - obj.source = "common.cc jpeg_encoder.cc jpeg.cc module.cc" + obj.source = "src/common.cc src/jpeg_encoder.cc src/jpeg.cc src/module.cc" obj.uselib = "JPEG" def shutdown(): if Options.commands['clean']: if exists('jpeg.node'): unlink('jpeg.node') else: if exists('build/default/jpeg.node') and not exists('jpeg.node'): symlink('build/default/jpeg.node', 'jpeg.node')
pkrumins/node-jpeg
9086976f9b5508eda43366138421cc318ec4478e
factored node-jpeg
diff --git a/common.cc b/common.cc new file mode 100644 index 0000000..490241c --- /dev/null +++ b/common.cc @@ -0,0 +1,67 @@ +#include <cstdlib> +#include <cassert> +#include "common.h" + +using namespace v8; + +Handle<Value> +VException(const char *msg) { + HandleScope scope; + return ThrowException(Exception::Error(String::New(msg))); +} + +bool str_eq(const char *s1, const char *s2) +{ + return strcmp(s1, s2) == 0; +} + +unsigned char * +rgba_to_rgb(const unsigned char *rgba, int rgba_size) +{ + assert(rgba_size%4==0); + + int rgb_size = rgba_size*3/4; + unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*rgb_size); + if (!rgb) return NULL; + + for (int i=0,j=0; i<rgba_size; i+=4,j+=3) { + rgb[j] = rgba[i]; + rgb[j+1] = rgba[i+1]; + rgb[j+2] = rgba[i+2]; + } + return rgb; +} + +unsigned char * +bgra_to_rgb(const unsigned char *bgra, int bgra_size) +{ + assert(bgra_size%4==0); + + int rgb_size = bgra_size*3/4; + unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*rgb_size); + if (!rgb) return NULL; + + for (int i=0,j=0; i<bgra_size; i+=4,j+=3) { + rgb[j] = bgra[i+2]; + rgb[j+1] = bgra[i+1]; + rgb[j+2] = bgra[i]; + } + return rgb; +} + +unsigned char * +bgr_to_rgb(const unsigned char *bgr, int bgr_size) +{ + assert(bgr_size%3==0); + + unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*bgr_size); + if (!rgb) return NULL; + + for (int i=0; i<bgr_size; i+=3) { + rgb[i] = bgr[i+2]; + rgb[i+1] = bgr[i+1]; + rgb[i+2] = bgr[i]; + } + return rgb; +} + diff --git a/common.h b/common.h new file mode 100644 index 0000000..15168a2 --- /dev/null +++ b/common.h @@ -0,0 +1,17 @@ +#ifndef COMMON_H +#define COMMON_H + +#include <node.h> +#include <cstring> + +v8::Handle<v8::Value> VException(const char *msg); + +bool str_eq(const char *s1, const char *s2); +unsigned char *rgba_to_rgb(const unsigned char *rgba, int rgba_size); +unsigned char *bgra_to_rgb(const unsigned char *rgba, int bgra_size); +unsigned char *bgr_to_rgb(const unsigned char *rgb, int rgb_size); + +typedef enum { BUF_RGB, BUF_BGR, BUF_RGBA, BUF_BGRA } buffer_type; + +#endif + diff --git a/jpeg.cc b/jpeg.cc index 06fd4a6..a30a754 100644 --- a/jpeg.cc +++ b/jpeg.cc @@ -1,170 +1,94 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> -#include <cassert> + +#include "common.h" +#include "jpeg.h" +#include "jpeg_encoder.h" using namespace v8; using namespace node; -static Handle<Value> -VException(const char *msg) { +void +Jpeg::Initialize(v8::Handle<v8::Object> target) +{ HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} -static inline bool -str_eq(const char *s1, const char *s2) -{ - return strcmp(s1, s2) == 0; + Local<FunctionTemplate> t = FunctionTemplate::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } -typedef enum { BUF_RGB, BUF_BGR, BUF_RGBA, BUF_BGRA } buffer_type; +Jpeg::Jpeg(Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : + jpeg_encoder((unsigned char *)ddata->data(), wwidth, hheight, qquality, bbuf_type) {} -class Jpeg : public ObjectWrap { -private: - int width; - int height; - int quality; - buffer_type buf_type; - Buffer *data; - -public: - static void - Initialize(v8::Handle<v8::Object> target) - { - HandleScope scope; - - Local<FunctionTemplate> t = FunctionTemplate::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); - target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); - } +Handle<Value> +Jpeg::JpegEncode() +{ + HandleScope scope; - Jpeg(Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : - data(ddata), width(wwidth), height(hheight), quality(qquality), - buf_type(bbuf_type) {} - - static unsigned char * - rgba_to_rgb(const unsigned char *rgba, int rgba_size) - { - assert(rgba_size%4==0); - - int rgb_size = rgba_size*3/4; - unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*rgb_size); - if (!rgb) return NULL; - - for (int i=0,j=0;i<rgba_size;i+=4,j+=3) { - rgb[j] = rgba[i]; - rgb[j+1] = rgba[i+1]; - rgb[j+2] = rgba[i+2]; - } - return rgb; + try { + jpeg_encoder.encode(); + } + catch (const char *err) { + return VException(err); } - Handle<Value> JpegEncode() { - HandleScope scope; - - unsigned char *mem_dest; - unsigned long outsize = 0; - - struct jpeg_compress_struct cinfo; - struct jpeg_error_mgr jerr; - - cinfo.err = jpeg_std_error(&jerr); - - jpeg_create_compress(&cinfo); - jpeg_mem_dest(&cinfo, &mem_dest, &outsize); - - cinfo.image_width = width; - cinfo.image_height = height; - cinfo.input_components = 3; - cinfo.in_color_space = JCS_RGB; - - jpeg_set_defaults(&cinfo); - jpeg_set_quality(&cinfo, quality, TRUE); - jpeg_start_compress(&cinfo, TRUE); - - unsigned char *rgb_data; - if (buf_type == BUF_RGBA) { - rgb_data = rgba_to_rgb((unsigned char *)data->data(), width*height*4); - if (!rgb_data) return VException("malloc failed in rgba_to_rgb."); - } else { - rgb_data = (unsigned char *)data->data(); - } - - JSAMPROW row_pointer; - while (cinfo.next_scanline < cinfo.image_height) { - row_pointer = &rgb_data[cinfo.next_scanline*3*width]; - jpeg_write_scanlines(&cinfo, &row_pointer, 1); - } - - jpeg_finish_compress(&cinfo); - jpeg_destroy_compress(&cinfo); - - free(mem_dest); - if (buf_type == BUF_RGBA) free(rgb_data); + return scope.Close( + Encode(jpeg_encoder.get_jpeg(), jpeg_encoder.get_jpeg_len(), BINARY) + ); +} - return scope.Close(Encode((char *)mem_dest, outsize, BINARY)); - } +Handle<Value> +Jpeg::New(const Arguments &args) +{ + HandleScope scope; -protected: - static Handle<Value> - New(const Arguments& args) - { - HandleScope scope; - - if (args.Length() != 5) - return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); - if (!Buffer::HasInstance(args[0])) - return VException("First argument must be Buffer."); - if (!args[1]->IsInt32()) - return VException("Second argument must be integer width."); - if (!args[2]->IsInt32()) - return VException("Third argument must be integer height."); - if (!args[3]->IsInt32()) - return VException("Fourth argument must be integer quality."); - if (!args[4]->IsString()) - return VException("Fifth argument must be a string. Either 'rgb' or 'rgba'."); - - int w = args[1]->Int32Value(); - int h = args[2]->Int32Value(); - int quality = args[3]->Int32Value(); - String::AsciiValue bt(args[4]->ToString()); - - if (quality < 0 || quality > 100) - return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) - return VException("Fifth argument must be either 'rgb' or 'rgba'."); - - buffer_type buf_type; - if (str_eq(*bt, "rgb")) - buf_type = BUF_RGB; - else if (str_eq(*bt, "rgba")) - buf_type = BUF_RGBA; - else - return VException("Buffer type wasn't 'rgb' or 'rgba'"); - - Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); - Jpeg *jpeg = new Jpeg(data_buf, w, h, quality, buf_type); - jpeg->Wrap(args.This()); - return args.This(); - } + if (args.Length() != 5) + return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); + if (!Buffer::HasInstance(args[0])) + return VException("First argument must be Buffer."); + if (!args[1]->IsInt32()) + return VException("Second argument must be integer width."); + if (!args[2]->IsInt32()) + return VException("Third argument must be integer height."); + if (!args[3]->IsInt32()) + return VException("Fourth argument must be integer quality."); + if (!args[4]->IsString()) + return VException("Fifth argument must be a string. Either 'rgb' or 'rgba'."); + + int w = args[1]->Int32Value(); + int h = args[2]->Int32Value(); + int quality = args[3]->Int32Value(); + String::AsciiValue bt(args[4]->ToString()); + + if (quality < 0 || quality > 100) + return VException("Quality must be between 0 and 100 (inclusive)."); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) + return VException("Fifth argument must be either 'rgb' or 'rgba'."); - static Handle<Value> - JpegEncode(const Arguments& args) - { - HandleScope scope; - Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); - return jpeg->JpegEncode(); - } -}; + buffer_type buf_type; + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else + return VException("Buffer type wasn't 'rgb' or 'rgba'"); + + Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + Jpeg *jpeg = new Jpeg(data_buf, w, h, quality, buf_type); + jpeg->Wrap(args.This()); + return args.This(); +} -extern "C" void -init(Handle<Object> target) +Handle<Value> +Jpeg::JpegEncode(const Arguments& args) { HandleScope scope; - Jpeg::Initialize(target); + Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); + return jpeg->JpegEncode(); } diff --git a/jpeg.h b/jpeg.h new file mode 100644 index 0000000..532ea6c --- /dev/null +++ b/jpeg.h @@ -0,0 +1,22 @@ +#ifndef JPEG_H +#define JPEG_H + +#include <node.h> +#include <node_buffer.h> + +#include "jpeg_encoder.h" + +class Jpeg : public node::ObjectWrap { + JpegEncoder jpeg_encoder; + +public: + static void Initialize(v8::Handle<v8::Object> target); + Jpeg(node::Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type); + v8::Handle<v8::Value> JpegEncode(); + + static v8::Handle<v8::Value> New(const v8::Arguments &args); + static v8::Handle<v8::Value> JpegEncode(const v8::Arguments &args); +}; + +#endif + diff --git a/jpeg_encoder.cc b/jpeg_encoder.cc new file mode 100644 index 0000000..7ff7d8f --- /dev/null +++ b/jpeg_encoder.cc @@ -0,0 +1,77 @@ +#include "jpeg_encoder.h" + +JpegEncoder::JpegEncoder(unsigned char *ddata, int wwidth, int hheight, + int qquality, buffer_type bbuf_type) : + data(ddata), width(wwidth), height(hheight), quality(qquality), + buf_type(bbuf_type), + jpeg(NULL), jpeg_len(0) {} + +JpegEncoder::~JpegEncoder() { + free(jpeg); +} + +void +JpegEncoder::encode() +{ + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + + jpeg_create_compress(&cinfo); + jpeg_mem_dest(&cinfo, &jpeg, &jpeg_len); + + cinfo.image_width = width; + cinfo.image_height = height; + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, quality, TRUE); + jpeg_start_compress(&cinfo, TRUE); + + unsigned char *rgb_data; + if (buf_type == BUF_RGBA) { + rgb_data = rgba_to_rgb(data, width*height*4); + if (!rgb_data) throw "malloc failed in JpegEncoder::encode/rgba_to_rgb."; + } + else if (buf_type == BUF_BGRA) { + rgb_data = bgra_to_rgb(data, width*height*4); + if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgra_to_rgb."; + + } + else if (buf_type == BUF_BGR) { + rgb_data = bgr_to_rgb(data, width*height*3); + if (!rgb_data) throw "malloc failed in JpegEncoder::encode/bgr_to_rgb."; + } + else if (buf_type == BUF_RGB) { + rgb_data = data; + } + else { + throw "Unknown buf_type"; + } + + JSAMPROW row_pointer; + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer = &rgb_data[cinfo.next_scanline*3*width]; + jpeg_write_scanlines(&cinfo, &row_pointer, 1); + } + + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + + if (buf_type == BUF_RGBA || buf_type == BUF_BGRA) + free(rgb_data); +} + +const unsigned char * +JpegEncoder::get_jpeg() const +{ + return jpeg; +} + +unsigned int +JpegEncoder::get_jpeg_len() const +{ + return jpeg_len; +} diff --git a/jpeg_encoder.h b/jpeg_encoder.h new file mode 100644 index 0000000..cd148fc --- /dev/null +++ b/jpeg_encoder.h @@ -0,0 +1,28 @@ +#ifndef JPEG_ENCODER_H +#define JPEG_ENCODER_H + +#include <cstdio> +#include <cstdlib> +#include <jpeglib.h> +#include "common.h" + +class JpegEncoder { + int width, height, quality; + buffer_type buf_type; + unsigned char *data; + + unsigned char *jpeg; + long unsigned int jpeg_len; + +public: + JpegEncoder(unsigned char *ddata, int wwidth, int hheight, + int qquality, buffer_type bbuf_type); + ~JpegEncoder(); + + void encode(); + const unsigned char *get_jpeg() const; + unsigned int get_jpeg_len() const; +}; + +#endif + diff --git a/module.cc b/module.cc new file mode 100644 index 0000000..0de1509 --- /dev/null +++ b/module.cc @@ -0,0 +1,12 @@ +#include <node.h> +#include "jpeg.h" + +using namespace v8; + +extern "C" void +init(Handle<Object> target) +{ + HandleScope scope; + Jpeg::Initialize(target); +} + diff --git a/wscript b/wscript index 226ba93..442bb85 100644 --- a/wscript +++ b/wscript @@ -1,29 +1,29 @@ import Options from os import unlink, symlink, popen from os.path import exists srcdir = "." blddir = "build" VERSION = "0.0.1" def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.target = "jpeg" - obj.source = "jpeg.cc" + obj.source = "common.cc jpeg_encoder.cc jpeg.cc module.cc" obj.uselib = "JPEG" def shutdown(): if Options.commands['clean']: if exists('jpeg.node'): unlink('jpeg.node') else: if exists('build/default/jpeg.node') and not exists('jpeg.node'): symlink('build/default/jpeg.node', 'jpeg.node')
pkrumins/node-jpeg
efcef0f0edb5f95df0a68098374509e7e58585e0
better notation
diff --git a/jpeg.cc b/jpeg.cc index dbb0101..06fd4a6 100644 --- a/jpeg.cc +++ b/jpeg.cc @@ -1,154 +1,170 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> +#include <cassert> using namespace v8; using namespace node; static Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } -typedef enum { BUF_RGBA, BUF_RGB } buf_type_t; +static inline bool +str_eq(const char *s1, const char *s2) +{ + return strcmp(s1, s2) == 0; +} + +typedef enum { BUF_RGB, BUF_BGR, BUF_RGBA, BUF_BGRA } buffer_type; class Jpeg : public ObjectWrap { private: - int width_; - int height_; - int quality_; - buf_type_t buf_type_; - Buffer *rgba_; + int width; + int height; + int quality; + buffer_type buf_type; + Buffer *data; public: static void Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } - Jpeg(Buffer *rgba, int width, int height, int quality, buf_type_t buf_type) : - rgba_(rgba), width_(width), height_(height), quality_(quality), - buf_type_(buf_type) {} + Jpeg(Buffer *ddata, int wwidth, int hheight, int qquality, buffer_type bbuf_type) : + data(ddata), width(wwidth), height(hheight), quality(qquality), + buf_type(bbuf_type) {} static unsigned char * - rgba_to_rgb(unsigned char *rgba, int rgba_size) + rgba_to_rgb(const unsigned char *rgba, int rgba_size) { - int rgb_size = rgba_size/4*3; - unsigned char *rgb = (unsigned char *)malloc(sizeof(unsigned char)*rgb_size); + assert(rgba_size%4==0); + + int rgb_size = rgba_size*3/4; + unsigned char *rgb = (unsigned char *)malloc(sizeof(*rgb)*rgb_size); if (!rgb) return NULL; - int i, j; - for (i=0,j=0;i<rgba_size;i+=4,j+=3) { - rgb[j] = *(rgba+i); - rgb[j+1] = *(rgba+i+1); - rgb[j+2] = *(rgba+i+2); + + for (int i=0,j=0;i<rgba_size;i+=4,j+=3) { + rgb[j] = rgba[i]; + rgb[j+1] = rgba[i+1]; + rgb[j+2] = rgba[i+2]; } return rgb; } Handle<Value> JpegEncode() { HandleScope scope; unsigned char *mem_dest; unsigned long outsize = 0; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &mem_dest, &outsize); - cinfo.image_width = width_; - cinfo.image_height = height_; + cinfo.image_width = width; + cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); - jpeg_set_quality(&cinfo, quality_, TRUE); + jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; - if (buf_type_ == BUF_RGBA) { - rgb_data = rgba_to_rgb((unsigned char *)rgba_->data(), width_*height_*4); + if (buf_type == BUF_RGBA) { + rgb_data = rgba_to_rgb((unsigned char *)data->data(), width*height*4); if (!rgb_data) return VException("malloc failed in rgba_to_rgb."); } else { - rgb_data = (unsigned char *)rgba_->data(); + rgb_data = (unsigned char *)data->data(); } JSAMPROW row_pointer; while (cinfo.next_scanline < cinfo.image_height) { - row_pointer = &rgb_data[cinfo.next_scanline*3*width_]; + row_pointer = &rgb_data[cinfo.next_scanline*3*width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); free(mem_dest); - if (buf_type_ == BUF_RGBA) free(rgb_data); + if (buf_type == BUF_RGBA) free(rgb_data); return scope.Close(Encode((char *)mem_dest, outsize, BINARY)); } protected: static Handle<Value> New(const Arguments& args) { HandleScope scope; if (args.Length() != 5) return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) return VException("Third argument must be integer height."); if (!args[3]->IsInt32()) return VException("Fourth argument must be integer quality."); if (!args[4]->IsString()) - return VException("Fifth argument must be a string. Either 'rgba' or 'rgb'."); + return VException("Fifth argument must be a string. Either 'rgb' or 'rgba'."); int w = args[1]->Int32Value(); int h = args[2]->Int32Value(); int quality = args[3]->Int32Value(); String::AsciiValue bt(args[4]->ToString()); if (quality < 0 || quality > 100) return VException("Quality must be between 0 and 100 (inclusive)."); - if (!(strcmp(*bt, "rgb") == 0 || strcmp(*bt, "rgba") == 0)) - return VException("Fifth argument must be either 'rgba' or 'rgb'."); - buf_type_t buf_type = (strcmp(*bt, "rgb") == 0) ? BUF_RGB : BUF_RGBA; - - Buffer *rgba = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); - Jpeg *jpeg = new Jpeg(rgba, w, h, quality, buf_type); + if (!(str_eq(*bt, "rgb") || str_eq(*bt, "rgba"))) + return VException("Fifth argument must be either 'rgb' or 'rgba'."); + + buffer_type buf_type; + if (str_eq(*bt, "rgb")) + buf_type = BUF_RGB; + else if (str_eq(*bt, "rgba")) + buf_type = BUF_RGBA; + else + return VException("Buffer type wasn't 'rgb' or 'rgba'"); + + Buffer *data_buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + Jpeg *jpeg = new Jpeg(data_buf, w, h, quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } static Handle<Value> JpegEncode(const Arguments& args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return jpeg->JpegEncode(); } }; extern "C" void init(Handle<Object> target) { HandleScope scope; Jpeg::Initialize(target); }
pkrumins/node-jpeg
b1fa21d392ef7b38332966e608b1301bec15aca1
remove comma from package.json
diff --git a/package.json b/package.json index 8c94570..3d70dd8 100644 --- a/package.json +++ b/package.json @@ -1,42 +1,42 @@ { "name": "jpeg", "version": "1.0.0", "main": "jpeg", "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", "picture" ], "maintainers": [ { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" } ], "licenses": [ { - "type": "MIT", + "type": "MIT" } ], "repositories": [ { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" } ], "directories": { "examples": "examples" }, "engines": { "node": ">=0.1.93" }, "scripts": { "install": "node-waf configure build" } }
pkrumins/node-jpeg
629cff265b14f3007483f9fc2ea483b9bcee09f7
added .npmignore
diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..b969101 --- /dev/null +++ b/.npmignore @@ -0,0 +1,3 @@ +build +discovery +jpeg.node
pkrumins/node-jpeg
cb154dc4161dd9290feedc32acf3c30848ed2f3c
package.json npm ready
diff --git a/package.json b/package.json index 3499752..8c94570 100644 --- a/package.json +++ b/package.json @@ -1,43 +1,42 @@ { - "name": "node-jpeg", - "version": "1.0", - "description": "A C++ module for node-js that converts an RGBA buffer to a JPEG image (in memory).", + "name": "jpeg", + "version": "1.0.0", + "main": "jpeg", + "description": "A C++ module for node-js that converts RGB and RGBA buffers to a JPEG images (in memory).", "keywords": [ "jpg", "rgba", "rgb", "image", - "picture", - "node", - "nodejs" + "picture" ], "maintainers": [ { "name": "Peteris Krumins", "email": "[email protected]", "web": "http://www.catonmat.net", "twitter": "pkrumins" } ], "licenses": [ { - "type": "GPLv2", - "url": "http://www.example.org/licenses/gpl.html" + "type": "MIT", } ], "repositories": [ { "type": "git", "url": "http://github.com/pkrumins/node-jpeg.git" } - "dependencies": { - "libjpeg": "8b" - }, + ], "directories": { "examples": "examples" }, "engines": { "node": ">=0.1.93" + }, + "scripts": { + "install": "node-waf configure build" } }
pkrumins/node-jpeg
84f72253e1758e3db9c505929168f9dfa1ee3ea4
V8 exceptions get returned not thrown, so I had to modify the code to return them
diff --git a/jpeg.cc b/jpeg.cc index 498dc05..dbb0101 100644 --- a/jpeg.cc +++ b/jpeg.cc @@ -1,143 +1,154 @@ #include <node.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> using namespace v8; using namespace node; +static Handle<Value> +VException(const char *msg) { + HandleScope scope; + return ThrowException(Exception::Error(String::New(msg))); +} + typedef enum { BUF_RGBA, BUF_RGB } buf_type_t; class Jpeg : public ObjectWrap { private: int width_; int height_; int quality_; buf_type_t buf_type_; Buffer *rgba_; public: static void Initialize(v8::Handle<v8::Object> target) { HandleScope scope; + Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg(Buffer *rgba, int width, int height, int quality, buf_type_t buf_type) : rgba_(rgba), width_(width), height_(height), quality_(quality), - buf_type_(buf_type) { } + buf_type_(buf_type) {} static unsigned char * rgba_to_rgb(unsigned char *rgba, int rgba_size) { int rgb_size = rgba_size/4*3; unsigned char *rgb = (unsigned char *)malloc(sizeof(unsigned char)*rgb_size); if (!rgb) return NULL; int i, j; for (i=0,j=0;i<rgba_size;i+=4,j+=3) { rgb[j] = *(rgba+i); rgb[j+1] = *(rgba+i+1); rgb[j+2] = *(rgba+i+2); } return rgb; } Handle<Value> JpegEncode() { HandleScope scope; unsigned char *mem_dest; unsigned long outsize = 0; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &mem_dest, &outsize); cinfo.image_width = width_; cinfo.image_height = height_; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality_, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type_ == BUF_RGBA) { rgb_data = rgba_to_rgb((unsigned char *)rgba_->data(), width_*height_*4); + if (!rgb_data) return VException("malloc failed in rgba_to_rgb."); } else { rgb_data = (unsigned char *)rgba_->data(); } JSAMPROW row_pointer; while (cinfo.next_scanline < cinfo.image_height) { row_pointer = &rgb_data[cinfo.next_scanline*3*width_]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); free(mem_dest); if (buf_type_ == BUF_RGBA) free(rgb_data); return scope.Close(Encode((char *)mem_dest, outsize, BINARY)); } protected: static Handle<Value> New(const Arguments& args) { HandleScope scope; if (args.Length() != 5) - ThrowException(Exception::Error(String::New("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"))); + return VException("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"); if (!Buffer::HasInstance(args[0])) - ThrowException(Exception::Error(String::New("First argument must be Buffer."))); + return VException("First argument must be Buffer."); if (!args[1]->IsInt32()) - ThrowException(Exception::Error(String::New("Second argument must be integer width."))); + return VException("Second argument must be integer width."); if (!args[2]->IsInt32()) - ThrowException(Exception::Error(String::New("Third argument must be integer height."))); + return VException("Third argument must be integer height."); if (!args[3]->IsInt32()) - ThrowException(Exception::Error(String::New("Fourth argument must be integer quality."))); - int quality = args[3]->Int32Value(); - if (quality < 0 || quality > 100) - ThrowException(Exception::Error(String::New("Quality must be between 0 and 100 (inclusive)."))); + return VException("Fourth argument must be integer quality."); if (!args[4]->IsString()) - ThrowException(Exception::Error(String::New("Fifth argument must be a string. Either 'rgba' or 'rgb'."))); + return VException("Fifth argument must be a string. Either 'rgba' or 'rgb'."); + + int w = args[1]->Int32Value(); + int h = args[2]->Int32Value(); + int quality = args[3]->Int32Value(); String::AsciiValue bt(args[4]->ToString()); + + if (quality < 0 || quality > 100) + return VException("Quality must be between 0 and 100 (inclusive)."); if (!(strcmp(*bt, "rgb") == 0 || strcmp(*bt, "rgba") == 0)) - ThrowException(Exception::Error(String::New("Fifth argument must be either 'rgba' or 'rgb'."))); + return VException("Fifth argument must be either 'rgba' or 'rgb'."); buf_type_t buf_type = (strcmp(*bt, "rgb") == 0) ? BUF_RGB : BUF_RGBA; Buffer *rgba = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); - Jpeg *jpeg = new Jpeg(rgba, args[1]->Int32Value(), - args[2]->Int32Value(), quality, buf_type); + Jpeg *jpeg = new Jpeg(rgba, w, h, quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } static Handle<Value> JpegEncode(const Arguments& args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); return jpeg->JpegEncode(); } }; extern "C" void init(Handle<Object> target) { HandleScope scope; Jpeg::Initialize(target); }
pkrumins/node-jpeg
ac3591d5f13968be94e3c5baadec44ea8912383b
discovery/ is hacks to figure out how stuff works, before coding anything else up
diff --git a/discovery/jpeg.c b/discovery/jpeg.c new file mode 100644 index 0000000..e9288fe --- /dev/null +++ b/discovery/jpeg.c @@ -0,0 +1,140 @@ +#include <stdio.h> +#include <stdlib.h> +#include <jpeglib.h> + +#define WIDTH 720 +#define HEIGHT 400 + +#define SIZE 720*400*4 + +#define OUTFILE "jpeg.jpeg" + +unsigned char *rgba_to_rgb(unsigned char *rgba, int rgba_size); +void jpeg_write_file(unsigned char *gba, int quality); +void jpeg_write_mem(unsigned char *gba, int quality); + +int main() +{ + FILE *f = fopen("./rgba-terminal.dat", "rb"); + if (!f) { + printf("Couldn't open rgba-terminal.dat\n"); + exit(1); + } + + unsigned char buf[SIZE]; + int read = fread(buf, sizeof(unsigned char), SIZE, f); + printf("Read %d bytes.\n", read); + fclose(f); + + unsigned char *rgb = rgba_to_rgb(buf, SIZE); + + //jpeg_write_file(rgb, 70); + jpeg_write_mem(rgb, 70); + + free(rgb); + + return 0; +} + +unsigned char * +rgba_to_rgb(unsigned char *rgba, int rgba_size) +{ + int rgb_size = rgba_size/4*3; + unsigned char *rgb = malloc(sizeof(unsigned char)*rgb_size); + if (!rgb) return NULL; + int i, j; + for (i=0,j=0;i<rgba_size;i+=4,j+=3) { + rgb[j] = *(rgba+i); + rgb[j+1] = *(rgba+i+1); + rgb[j+2] = *(rgba+i+2); + } + return rgb; +} + +void jpeg_write_file(unsigned char *rgb, int quality) { + printf("Writing to %s.\n", OUTFILE); + + FILE *f = fopen(OUTFILE, "wb"); + if (!f) { + printf("Couldn't open %s\n", OUTFILE); + exit(1); + } + + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + + jpeg_create_compress(&cinfo); + jpeg_stdio_dest(&cinfo, f); + + cinfo.image_width = WIDTH; + cinfo.image_height = HEIGHT; + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + + jpeg_set_quality(&cinfo, quality, TRUE); + + jpeg_start_compress(&cinfo, TRUE); + + JSAMPROW row_pointer[1]; + + int row_stride = WIDTH * 3; + + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer[0] = &rgb[cinfo.next_scanline*row_stride]; + jpeg_write_scanlines(&cinfo, row_pointer, 1); + } + + jpeg_finish_compress(&cinfo); + fclose(f); + + jpeg_destroy_compress(&cinfo); +} + +void jpeg_write_mem(unsigned char *rgb, int quality) { + unsigned char *mem_dest; + unsigned long outsize = 0; + + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + + jpeg_create_compress(&cinfo); + jpeg_mem_dest(&cinfo, &mem_dest, &outsize); + + cinfo.image_width = WIDTH; + cinfo.image_height = HEIGHT; + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + + jpeg_set_quality(&cinfo, quality, TRUE); + + jpeg_start_compress(&cinfo, TRUE); + + JSAMPROW row_pointer[1]; + + int row_stride = WIDTH * 3; + + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer[0] = &rgb[cinfo.next_scanline*row_stride]; + jpeg_write_scanlines(&cinfo, row_pointer, 1); + } + + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + + FILE *out = fopen("jpeg-mem.jpeg", "w+"); + if (!out) { + printf("damn\n"); + } + fwrite(mem_dest, outsize, 1, out); + free(mem_dest); + fclose(out); +} +
pkrumins/node-jpeg
dc22ecf526b667863a6f675c6966eec2d80e83c8
no more events.
diff --git a/examples/jpeg-example.js b/examples/jpeg-example.js index ba6657b..3e8dded 100644 --- a/examples/jpeg-example.js +++ b/examples/jpeg-example.js @@ -1,24 +1,14 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; // the rgba-terminal.dat file is 1152000 bytes long. var rgba = new Buffer(1152000); rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); var jpeg = new Jpeg(rgba, 720, 400, 70, 'rgba'); +var jpeg_img = jpeg.encode(); -var fd = fs.openSync('./jpeg.jpeg', 'w+', 0660); -var total = 0, written = 0; -jpeg.addListener('data', function(chunk, length) { - sys.log('Got a chunk. Size: ' + length); - written += fs.writeSync(fd, chunk, written, 'binary'); - total += length; -}); -jpeg.addListener('end', function() { - fs.closeSync(fd); - sys.log('Total: ' + total + ' bytes. Written: ' + written + ' bytes.'); -}); -jpeg.encode(); +fs.writeFileSync('./jpeg.jpeg', jpeg_img, 'binary'); diff --git a/examples/jpeg-example2.js b/examples/jpeg-example2.js index dd5930a..65031a7 100644 --- a/examples/jpeg-example2.js +++ b/examples/jpeg-example2.js @@ -1,29 +1,22 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; var WIDTH = 400, HEIGHT = 300; var rgba = new Buffer(WIDTH*HEIGHT*3); for (var i=0; i<HEIGHT; i++) { for (var j=0; j<WIDTH; j++) { rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; } } var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 50, 'rgb'); +var jpeg_img = jpeg.encode(); -var fd = fs.openSync('./jpeg-gradient.jpeg', 'w+', 0660); -var written = 0; -jpeg.addListener('data', function(chunk, length) { - written += fs.writeSync(fd, chunk, written, 'binary'); -}); -jpeg.addListener('end', function() { - fs.closeSync(fd); -}); -jpeg.encode(); +fs.writeFileSync('./jpeg-gradient.jpeg', jpeg_img, 'binary'); diff --git a/jpeg.cc b/jpeg.cc index 6cb01f2..498dc05 100644 --- a/jpeg.cc +++ b/jpeg.cc @@ -1,160 +1,143 @@ #include <node.h> -#include <node_events.h> #include <node_buffer.h> #include <jpeglib.h> #include <cstdlib> #include <cstring> using namespace v8; using namespace node; -static Persistent<String> end_symbol; -static Persistent<String> data_symbol; - typedef enum { BUF_RGBA, BUF_RGB } buf_type_t; -class Jpeg : public EventEmitter { +class Jpeg : public ObjectWrap { private: int width_; int height_; int quality_; buf_type_t buf_type_; Buffer *rgba_; public: static void Initialize(v8::Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); - t->Inherit(EventEmitter::constructor_template); t->InstanceTemplate()->SetInternalFieldCount(1); - end_symbol = NODE_PSYMBOL("end"); - data_symbol = NODE_PSYMBOL("data"); NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); } Jpeg(Buffer *rgba, int width, int height, int quality, buf_type_t buf_type) : - EventEmitter(), rgba_(rgba), width_(width), height_(height), - quality_(quality), buf_type_(buf_type) { } + rgba_(rgba), width_(width), height_(height), quality_(quality), + buf_type_(buf_type) { } static unsigned char * rgba_to_rgb(unsigned char *rgba, int rgba_size) { int rgb_size = rgba_size/4*3; unsigned char *rgb = (unsigned char *)malloc(sizeof(unsigned char)*rgb_size); if (!rgb) return NULL; int i, j; for (i=0,j=0;i<rgba_size;i+=4,j+=3) { rgb[j] = *(rgba+i); rgb[j+1] = *(rgba+i+1); rgb[j+2] = *(rgba+i+2); } return rgb; } - void JpegEncode() { + Handle<Value> JpegEncode() { + HandleScope scope; + unsigned char *mem_dest; unsigned long outsize = 0; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_mem_dest(&cinfo, &mem_dest, &outsize); cinfo.image_width = width_; cinfo.image_height = height_; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality_, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char *rgb_data; if (buf_type_ == BUF_RGBA) { rgb_data = rgba_to_rgb((unsigned char *)rgba_->data(), width_*height_*4); } else { rgb_data = (unsigned char *)rgba_->data(); } - JSAMPROW row_pointer[1]; + JSAMPROW row_pointer; while (cinfo.next_scanline < cinfo.image_height) { - row_pointer[0] = &rgb_data[cinfo.next_scanline*3*width_]; - jpeg_write_scanlines(&cinfo, row_pointer, 1); + row_pointer = &rgb_data[cinfo.next_scanline*3*width_]; + jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); free(mem_dest); if (buf_type_ == BUF_RGBA) free(rgb_data); - Local<Value> args[2] = { - Encode((char *)mem_dest, outsize, BINARY), - Integer::New(outsize) - }; - Emit(data_symbol, 2, args); - Emit(end_symbol, 0, NULL); + return scope.Close(Encode((char *)mem_dest, outsize, BINARY)); } protected: static Handle<Value> New(const Arguments& args) { HandleScope scope; if (args.Length() != 5) ThrowException(Exception::Error(String::New("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"))); if (!Buffer::HasInstance(args[0])) ThrowException(Exception::Error(String::New("First argument must be Buffer."))); if (!args[1]->IsInt32()) ThrowException(Exception::Error(String::New("Second argument must be integer width."))); if (!args[2]->IsInt32()) ThrowException(Exception::Error(String::New("Third argument must be integer height."))); if (!args[3]->IsInt32()) ThrowException(Exception::Error(String::New("Fourth argument must be integer quality."))); int quality = args[3]->Int32Value(); if (quality < 0 || quality > 100) ThrowException(Exception::Error(String::New("Quality must be between 0 and 100 (inclusive)."))); if (!args[4]->IsString()) ThrowException(Exception::Error(String::New("Fifth argument must be a string. Either 'rgba' or 'rgb'."))); String::AsciiValue bt(args[4]->ToString()); if (!(strcmp(*bt, "rgb") == 0 || strcmp(*bt, "rgba") == 0)) ThrowException(Exception::Error(String::New("Fifth argument must be either 'rgba' or 'rgb'."))); - buf_type_t buf_type; - if (strcmp(*bt, "rgb") == 0) { - buf_type = BUF_RGB; - } - else { - buf_type = BUF_RGBA; - } + buf_type_t buf_type = (strcmp(*bt, "rgb") == 0) ? BUF_RGB : BUF_RGBA; Buffer *rgba = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); - Jpeg *jpeg = new Jpeg(rgba, args[1]->Int32Value(), args[2]->Int32Value(), - quality, buf_type); + Jpeg *jpeg = new Jpeg(rgba, args[1]->Int32Value(), + args[2]->Int32Value(), quality, buf_type); jpeg->Wrap(args.This()); return args.This(); } static Handle<Value> JpegEncode(const Arguments& args) { HandleScope scope; Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); - jpeg->JpegEncode(); - return Undefined(); + return jpeg->JpegEncode(); } }; extern "C" void init(Handle<Object> target) { HandleScope scope; Jpeg::Initialize(target); } diff --git a/readme.txt b/readme.txt index 1ad54e4..b5215a3 100644 --- a/readme.txt +++ b/readme.txt @@ -1,39 +1,39 @@ This is a node.js module, writen in C++, that uses libjpeg to produce a JPEG -image from a buffer of RGBA or RGB values. Since JPEG has no notion of A (alpha), -the module always uses just RGB values. +image (in memory) from a buffer of RGBA or RGB values. Since JPEG has no notion +of A (alpha), the module always uses just RGB values. It was written by Peteris Krumins ([email protected]). His blog is at http://www.catonmat.net -- good coders code, great reuse. ------------------------------------------------------------------------------ The module exports `Jpeg` object that takes 5 arguments in its constructor: var png = new Jpeg(buffer, width, height, quality, buffer_type); The first argument, `buffer`, is a nodee.js `Buffer` filled with RGBA or RGB values. The second argument is integer width of the image. The third argument is integer height of the image. The fourth argument is the quality of output image. The fifth argument is buffer type, either 'rgb' or 'rgba'. See `examples/` directory for examples. To get it compiled, you need to have libjpeg and node installed. Then just run node-waf configure build to build the Jpeg module. It will produce a `jpeg.node` file as the module. -See also http://github.com/pkrumins/node-png to produce PNG images. +See also http://github.com/pkrumins/node-png module that produces PNG images. ------------------------------------------------------------------------------ Have fun! Sincerely, Peteris Krumins http://www.catonmat.net
pkrumins/node-jpeg
0e0d3480ea20bf679b517dca3f427b3dd6cbd7a1
png is not jpeg
diff --git a/examples/jpeg-example2.js b/examples/jpeg-example2.js index 84b4ed8..dd5930a 100644 --- a/examples/jpeg-example2.js +++ b/examples/jpeg-example2.js @@ -1,29 +1,29 @@ var fs = require('fs'); var sys = require('sys'); var Jpeg = require('../jpeg').Jpeg; var Buffer = require('buffer').Buffer; var WIDTH = 400, HEIGHT = 300; var rgba = new Buffer(WIDTH*HEIGHT*3); for (var i=0; i<HEIGHT; i++) { for (var j=0; j<WIDTH; j++) { rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; } } -var png = new Jpeg(rgba, WIDTH, HEIGHT, 50, 'rgb'); +var jpeg = new Jpeg(rgba, WIDTH, HEIGHT, 50, 'rgb'); var fd = fs.openSync('./jpeg-gradient.jpeg', 'w+', 0660); var written = 0; -png.addListener('data', function(chunk, length) { +jpeg.addListener('data', function(chunk, length) { written += fs.writeSync(fd, chunk, written, 'binary'); }); -png.addListener('end', function() { +jpeg.addListener('end', function() { fs.closeSync(fd); }); -png.encode(); +jpeg.encode();
pkrumins/node-jpeg
ed33d83dc4d9c8f29d3aa118ca8bb506befc4594
it's working
diff --git a/examples/jpeg-example.js b/examples/jpeg-example.js new file mode 100644 index 0000000..ba6657b --- /dev/null +++ b/examples/jpeg-example.js @@ -0,0 +1,24 @@ +var fs = require('fs'); +var sys = require('sys'); +var Jpeg = require('../jpeg').Jpeg; +var Buffer = require('buffer').Buffer; + +// the rgba-terminal.dat file is 1152000 bytes long. +var rgba = new Buffer(1152000); +rgba.write(fs.readFileSync('./rgba-terminal.dat', 'binary'), 'binary'); + +var jpeg = new Jpeg(rgba, 720, 400, 70, 'rgba'); + +var fd = fs.openSync('./jpeg.jpeg', 'w+', 0660); +var total = 0, written = 0; +jpeg.addListener('data', function(chunk, length) { + sys.log('Got a chunk. Size: ' + length); + written += fs.writeSync(fd, chunk, written, 'binary'); + total += length; +}); +jpeg.addListener('end', function() { + fs.closeSync(fd); + sys.log('Total: ' + total + ' bytes. Written: ' + written + ' bytes.'); +}); +jpeg.encode(); + diff --git a/examples/jpeg-example2.js b/examples/jpeg-example2.js new file mode 100644 index 0000000..84b4ed8 --- /dev/null +++ b/examples/jpeg-example2.js @@ -0,0 +1,29 @@ +var fs = require('fs'); +var sys = require('sys'); +var Jpeg = require('../jpeg').Jpeg; +var Buffer = require('buffer').Buffer; + +var WIDTH = 400, HEIGHT = 300; + +var rgba = new Buffer(WIDTH*HEIGHT*3); + +for (var i=0; i<HEIGHT; i++) { + for (var j=0; j<WIDTH; j++) { + rgba[i*WIDTH*3 + j*3 + 0] = 255*j/WIDTH; + rgba[i*WIDTH*3 + j*3 + 1] = 255*i/HEIGHT; + rgba[i*WIDTH*3 + j*3 + 2] = 0xff/2; + } +} + +var png = new Jpeg(rgba, WIDTH, HEIGHT, 50, 'rgb'); + +var fd = fs.openSync('./jpeg-gradient.jpeg', 'w+', 0660); +var written = 0; +png.addListener('data', function(chunk, length) { + written += fs.writeSync(fd, chunk, written, 'binary'); +}); +png.addListener('end', function() { + fs.closeSync(fd); +}); +png.encode(); + diff --git a/examples/rgba-terminal.dat b/examples/rgba-terminal.dat new file mode 100644 index 0000000..0371887 Binary files /dev/null and b/examples/rgba-terminal.dat differ diff --git a/jpeg.cc b/jpeg.cc new file mode 100644 index 0000000..6cb01f2 --- /dev/null +++ b/jpeg.cc @@ -0,0 +1,160 @@ +#include <node.h> +#include <node_events.h> +#include <node_buffer.h> +#include <jpeglib.h> +#include <cstdlib> +#include <cstring> + +using namespace v8; +using namespace node; + +static Persistent<String> end_symbol; +static Persistent<String> data_symbol; + +typedef enum { BUF_RGBA, BUF_RGB } buf_type_t; + +class Jpeg : public EventEmitter { +private: + int width_; + int height_; + int quality_; + buf_type_t buf_type_; + Buffer *rgba_; + +public: + static void + Initialize(v8::Handle<v8::Object> target) + { + HandleScope scope; + Local<FunctionTemplate> t = FunctionTemplate::New(New); + t->Inherit(EventEmitter::constructor_template); + t->InstanceTemplate()->SetInternalFieldCount(1); + end_symbol = NODE_PSYMBOL("end"); + data_symbol = NODE_PSYMBOL("data"); + NODE_SET_PROTOTYPE_METHOD(t, "encode", JpegEncode); + target->Set(String::NewSymbol("Jpeg"), t->GetFunction()); + } + + Jpeg(Buffer *rgba, int width, int height, int quality, buf_type_t buf_type) : + EventEmitter(), rgba_(rgba), width_(width), height_(height), + quality_(quality), buf_type_(buf_type) { } + + static unsigned char * + rgba_to_rgb(unsigned char *rgba, int rgba_size) + { + int rgb_size = rgba_size/4*3; + unsigned char *rgb = (unsigned char *)malloc(sizeof(unsigned char)*rgb_size); + if (!rgb) return NULL; + int i, j; + for (i=0,j=0;i<rgba_size;i+=4,j+=3) { + rgb[j] = *(rgba+i); + rgb[j+1] = *(rgba+i+1); + rgb[j+2] = *(rgba+i+2); + } + return rgb; + } + + void JpegEncode() { + unsigned char *mem_dest; + unsigned long outsize = 0; + + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + + jpeg_create_compress(&cinfo); + jpeg_mem_dest(&cinfo, &mem_dest, &outsize); + + cinfo.image_width = width_; + cinfo.image_height = height_; + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, quality_, TRUE); + jpeg_start_compress(&cinfo, TRUE); + + unsigned char *rgb_data; + if (buf_type_ == BUF_RGBA) { + rgb_data = rgba_to_rgb((unsigned char *)rgba_->data(), width_*height_*4); + } else { + rgb_data = (unsigned char *)rgba_->data(); + } + + JSAMPROW row_pointer[1]; + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer[0] = &rgb_data[cinfo.next_scanline*3*width_]; + jpeg_write_scanlines(&cinfo, row_pointer, 1); + } + + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + + free(mem_dest); + if (buf_type_ == BUF_RGBA) free(rgb_data); + + Local<Value> args[2] = { + Encode((char *)mem_dest, outsize, BINARY), + Integer::New(outsize) + }; + Emit(data_symbol, 2, args); + Emit(end_symbol, 0, NULL); + } + +protected: + static Handle<Value> + New(const Arguments& args) + { + HandleScope scope; + + if (args.Length() != 5) + ThrowException(Exception::Error(String::New("Five arguments required - rgba/rgb buffer, width, height, quality, buffer type"))); + if (!Buffer::HasInstance(args[0])) + ThrowException(Exception::Error(String::New("First argument must be Buffer."))); + if (!args[1]->IsInt32()) + ThrowException(Exception::Error(String::New("Second argument must be integer width."))); + if (!args[2]->IsInt32()) + ThrowException(Exception::Error(String::New("Third argument must be integer height."))); + if (!args[3]->IsInt32()) + ThrowException(Exception::Error(String::New("Fourth argument must be integer quality."))); + int quality = args[3]->Int32Value(); + if (quality < 0 || quality > 100) + ThrowException(Exception::Error(String::New("Quality must be between 0 and 100 (inclusive)."))); + if (!args[4]->IsString()) + ThrowException(Exception::Error(String::New("Fifth argument must be a string. Either 'rgba' or 'rgb'."))); + String::AsciiValue bt(args[4]->ToString()); + if (!(strcmp(*bt, "rgb") == 0 || strcmp(*bt, "rgba") == 0)) + ThrowException(Exception::Error(String::New("Fifth argument must be either 'rgba' or 'rgb'."))); + buf_type_t buf_type; + if (strcmp(*bt, "rgb") == 0) { + buf_type = BUF_RGB; + } + else { + buf_type = BUF_RGBA; + } + + Buffer *rgba = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); + Jpeg *jpeg = new Jpeg(rgba, args[1]->Int32Value(), args[2]->Int32Value(), + quality, buf_type); + jpeg->Wrap(args.This()); + return args.This(); + } + + static Handle<Value> + JpegEncode(const Arguments& args) + { + HandleScope scope; + Jpeg *jpeg = ObjectWrap::Unwrap<Jpeg>(args.This()); + jpeg->JpegEncode(); + return Undefined(); + } +}; + +extern "C" void +init(Handle<Object> target) +{ + HandleScope scope; + Jpeg::Initialize(target); +} + diff --git a/package.json b/package.json new file mode 100644 index 0000000..3499752 --- /dev/null +++ b/package.json @@ -0,0 +1,43 @@ +{ + "name": "node-jpeg", + "version": "1.0", + "description": "A C++ module for node-js that converts an RGBA buffer to a JPEG image (in memory).", + "keywords": [ + "jpg", + "rgba", + "rgb", + "image", + "picture", + "node", + "nodejs" + ], + "maintainers": [ + { + "name": "Peteris Krumins", + "email": "[email protected]", + "web": "http://www.catonmat.net", + "twitter": "pkrumins" + } + ], + "licenses": [ + { + "type": "GPLv2", + "url": "http://www.example.org/licenses/gpl.html" + } + ], + "repositories": [ + { + "type": "git", + "url": "http://github.com/pkrumins/node-jpeg.git" + } + "dependencies": { + "libjpeg": "8b" + }, + "directories": { + "examples": "examples" + }, + "engines": { + "node": ">=0.1.93" + } +} + diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..2b5a1b3 --- /dev/null +++ b/readme.txt @@ -0,0 +1,38 @@ +This is a node.js module, writen in C++, that uses libjpeg to produce a JPEG +image from a buffer of RGBA or RGB values. Since JPEG has no notion of A (alpha), +the module always uses just RGB values. + +It was written by Peteris Krumins ([email protected]). +His blog is at http://www.catonmat.net -- good coders code, great reuse. + +------------------------------------------------------------------------------ + +The module exports `Jpeg` object that takes 5 arguments in its constructor: + + var png = new Jpeg(buffer, width, height, quality, buffer_type); + +The first argument, `buffer`, is a nodee.js `Buffer` filled with RGBA or RGB +values. +The second argument is integer width of the image. +The third argument is integer height of the image. +The fourth argument is the quality of output image. +The fifth argument is buffer type, either 'rgb' or 'rgba'. + +See `examples/` directory for examples. + +To get it compiled, you need to have libjpeg and node installed. Then just run + + node-waf configure build + +to build the Jpeg module. It will produce a `jpeg.node` file as the module. + + +------------------------------------------------------------------------------ + +Have fun! + + +Sincerely, +Peteris Krumins +http://www.catonmat.net + diff --git a/wscript b/wscript new file mode 100644 index 0000000..226ba93 --- /dev/null +++ b/wscript @@ -0,0 +1,29 @@ +import Options +from os import unlink, symlink, popen +from os.path import exists + +srcdir = "." +blddir = "build" +VERSION = "0.0.1" + +def set_options(opt): + opt.tool_options("compiler_cxx") + +def configure(conf): + conf.check_tool("compiler_cxx") + conf.check_tool("node_addon") + conf.check(lib='jpeg', libpath=['/lib', '/usr/lib', '/usr/local/lib', '/usr/local/libjpeg/lib', '/usr/local/pkg/jpeg-8b/lib']) + +def build(bld): + obj = bld.new_task_gen("cxx", "shlib", "node_addon") + obj.target = "jpeg" + obj.source = "jpeg.cc" + obj.uselib = "JPEG" + +def shutdown(): + if Options.commands['clean']: + if exists('jpeg.node'): unlink('jpeg.node') + else: + if exists('build/default/jpeg.node') and not exists('jpeg.node'): + symlink('build/default/jpeg.node', 'jpeg.node') +
cincinnatirb/Suggestion-Box
6951b20e4a3aa5fb2ff13d4edf32cb020df8b254
Don't use http urls for git repositories
diff --git a/Gemfile b/Gemfile index b856465..deb13a5 100644 --- a/Gemfile +++ b/Gemfile @@ -1,14 +1,14 @@ source :gemcutter gem "rails", "3.0.0" gem "sqlite3-ruby", :require => "sqlite3" -gem 'formtastic', :git => "http://github.com/justinfrench/formtastic.git", :branch => "rails3" +gem 'formtastic', :git => "git://github.com/justinfrench/formtastic.git", :branch => "rails3" gem "escape_utils" group :test do gem "factory_girl_rails" gem "shoulda" gem "flexmock" gem "capybara" end diff --git a/Gemfile.lock b/Gemfile.lock index 8e6fc7e..56acb5e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,113 +1,113 @@ GIT - remote: http://github.com/justinfrench/formtastic.git - revision: 42b4eb8 + remote: git://github.com/justinfrench/formtastic.git + revision: e42d256ebe7fdbd3881665d94ce54cf061a9186f branch: rails3 specs: - formtastic (1.0.0) + formtastic (1.1.0.beta) actionpack (>= 2.3.0) activesupport (>= 2.3.0) i18n (>= 0.4.0) GEM remote: http://rubygems.org/ specs: abstract (1.0.0) actionmailer (3.0.0) actionpack (= 3.0.0) mail (~> 2.2.5) actionpack (3.0.0) activemodel (= 3.0.0) activesupport (= 3.0.0) builder (~> 2.1.2) erubis (~> 2.6.6) i18n (~> 0.4.1) rack (~> 1.2.1) rack-mount (~> 0.6.12) rack-test (~> 0.5.4) tzinfo (~> 0.3.23) activemodel (3.0.0) activesupport (= 3.0.0) builder (~> 2.1.2) i18n (~> 0.4.1) activerecord (3.0.0) activemodel (= 3.0.0) activesupport (= 3.0.0) arel (~> 1.0.0) tzinfo (~> 0.3.23) activeresource (3.0.0) activemodel (= 3.0.0) activesupport (= 3.0.0) activesupport (3.0.0) arel (1.0.1) activesupport (~> 3.0.0) builder (2.1.2) capybara (0.3.9) culerity (>= 0.2.4) mime-types (>= 1.16) nokogiri (>= 1.3.3) rack (>= 1.0.0) rack-test (>= 0.5.4) selenium-webdriver (>= 0.0.3) culerity (0.2.10) erubis (2.6.6) abstract (>= 1.0.0) escape_utils (0.1.5) factory_girl (1.3.2) factory_girl_rails (1.0) factory_girl (~> 1.3) rails (>= 3.0.0.beta4) ffi (0.6.3) rake (>= 0.8.7) flexmock (0.8.7) i18n (0.4.1) json_pure (1.4.6) mail (2.2.5) activesupport (>= 2.3.6) mime-types treetop (>= 1.4.5) mime-types (1.16) nokogiri (1.4.3.1) polyglot (0.3.1) rack (1.2.1) rack-mount (0.6.13) rack (>= 1.0.0) rack-test (0.5.4) rack (>= 1.0) rails (3.0.0) actionmailer (= 3.0.0) actionpack (= 3.0.0) activerecord (= 3.0.0) activeresource (= 3.0.0) activesupport (= 3.0.0) bundler (~> 1.0.0) railties (= 3.0.0) railties (3.0.0) actionpack (= 3.0.0) activesupport (= 3.0.0) rake (>= 0.8.4) thor (~> 0.14.0) rake (0.8.7) rubyzip (0.9.4) selenium-webdriver (0.0.27) ffi (>= 0.6.1) json_pure rubyzip shoulda (2.11.3) sqlite3-ruby (1.3.1) thor (0.14.0) treetop (1.4.8) polyglot (>= 0.3.1) tzinfo (0.3.23) PLATFORMS ruby DEPENDENCIES capybara escape_utils factory_girl_rails flexmock formtastic! rails (= 3.0.0) shoulda sqlite3-ruby
cincinnatirb/Suggestion-Box
7fa12c55eb4c9f29308b9fae28fc4e1859a0863f
Upgrading to Rails 3.0.0 final
diff --git a/Gemfile b/Gemfile index 7091e47..b856465 100644 --- a/Gemfile +++ b/Gemfile @@ -1,14 +1,14 @@ source :gemcutter -gem "rails", "3.0.0.rc" +gem "rails", "3.0.0" gem "sqlite3-ruby", :require => "sqlite3" gem 'formtastic', :git => "http://github.com/justinfrench/formtastic.git", :branch => "rails3" gem "escape_utils" group :test do gem "factory_girl_rails" gem "shoulda" gem "flexmock" gem "capybara" end diff --git a/Gemfile.lock b/Gemfile.lock index 5a023b3..8e6fc7e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,113 +1,113 @@ GIT remote: http://github.com/justinfrench/formtastic.git revision: 42b4eb8 branch: rails3 specs: formtastic (1.0.0) actionpack (>= 2.3.0) activesupport (>= 2.3.0) i18n (>= 0.4.0) GEM remote: http://rubygems.org/ specs: abstract (1.0.0) - actionmailer (3.0.0.rc) - actionpack (= 3.0.0.rc) + actionmailer (3.0.0) + actionpack (= 3.0.0) mail (~> 2.2.5) - actionpack (3.0.0.rc) - activemodel (= 3.0.0.rc) - activesupport (= 3.0.0.rc) + actionpack (3.0.0) + activemodel (= 3.0.0) + activesupport (= 3.0.0) builder (~> 2.1.2) erubis (~> 2.6.6) i18n (~> 0.4.1) rack (~> 1.2.1) - rack-mount (~> 0.6.9) + rack-mount (~> 0.6.12) rack-test (~> 0.5.4) - tzinfo (~> 0.3.22) - activemodel (3.0.0.rc) - activesupport (= 3.0.0.rc) + tzinfo (~> 0.3.23) + activemodel (3.0.0) + activesupport (= 3.0.0) builder (~> 2.1.2) i18n (~> 0.4.1) - activerecord (3.0.0.rc) - activemodel (= 3.0.0.rc) - activesupport (= 3.0.0.rc) - arel (~> 0.4.0) - tzinfo (~> 0.3.22) - activeresource (3.0.0.rc) - activemodel (= 3.0.0.rc) - activesupport (= 3.0.0.rc) - activesupport (3.0.0.rc) - arel (0.4.0) - activesupport (>= 3.0.0.beta) + activerecord (3.0.0) + activemodel (= 3.0.0) + activesupport (= 3.0.0) + arel (~> 1.0.0) + tzinfo (~> 0.3.23) + activeresource (3.0.0) + activemodel (= 3.0.0) + activesupport (= 3.0.0) + activesupport (3.0.0) + arel (1.0.1) + activesupport (~> 3.0.0) builder (2.1.2) capybara (0.3.9) culerity (>= 0.2.4) mime-types (>= 1.16) nokogiri (>= 1.3.3) rack (>= 1.0.0) rack-test (>= 0.5.4) selenium-webdriver (>= 0.0.3) culerity (0.2.10) erubis (2.6.6) abstract (>= 1.0.0) escape_utils (0.1.5) factory_girl (1.3.2) factory_girl_rails (1.0) factory_girl (~> 1.3) rails (>= 3.0.0.beta4) ffi (0.6.3) rake (>= 0.8.7) flexmock (0.8.7) i18n (0.4.1) json_pure (1.4.6) mail (2.2.5) activesupport (>= 2.3.6) mime-types treetop (>= 1.4.5) mime-types (1.16) nokogiri (1.4.3.1) polyglot (0.3.1) rack (1.2.1) - rack-mount (0.6.9) + rack-mount (0.6.13) rack (>= 1.0.0) rack-test (0.5.4) rack (>= 1.0) - rails (3.0.0.rc) - actionmailer (= 3.0.0.rc) - actionpack (= 3.0.0.rc) - activerecord (= 3.0.0.rc) - activeresource (= 3.0.0.rc) - activesupport (= 3.0.0.rc) - bundler (>= 1.0.0.rc.1) - railties (= 3.0.0.rc) - railties (3.0.0.rc) - actionpack (= 3.0.0.rc) - activesupport (= 3.0.0.rc) - rake (>= 0.8.3) + rails (3.0.0) + actionmailer (= 3.0.0) + actionpack (= 3.0.0) + activerecord (= 3.0.0) + activeresource (= 3.0.0) + activesupport (= 3.0.0) + bundler (~> 1.0.0) + railties (= 3.0.0) + railties (3.0.0) + actionpack (= 3.0.0) + activesupport (= 3.0.0) + rake (>= 0.8.4) thor (~> 0.14.0) rake (0.8.7) rubyzip (0.9.4) selenium-webdriver (0.0.27) ffi (>= 0.6.1) json_pure rubyzip shoulda (2.11.3) sqlite3-ruby (1.3.1) thor (0.14.0) treetop (1.4.8) polyglot (>= 0.3.1) - tzinfo (0.3.22) + tzinfo (0.3.23) PLATFORMS ruby DEPENDENCIES capybara escape_utils factory_girl_rails flexmock formtastic! - rails (= 3.0.0.rc) + rails (= 3.0.0) shoulda sqlite3-ruby diff --git a/vendor/cache/actionmailer-3.0.0.gem b/vendor/cache/actionmailer-3.0.0.gem new file mode 100644 index 0000000..c5b5934 Binary files /dev/null and b/vendor/cache/actionmailer-3.0.0.gem differ diff --git a/vendor/cache/actionmailer-3.0.0.rc.gem b/vendor/cache/actionmailer-3.0.0.rc.gem deleted file mode 100644 index b6dc177..0000000 Binary files a/vendor/cache/actionmailer-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/actionpack-3.0.0.gem b/vendor/cache/actionpack-3.0.0.gem new file mode 100644 index 0000000..1ce361b Binary files /dev/null and b/vendor/cache/actionpack-3.0.0.gem differ diff --git a/vendor/cache/actionpack-3.0.0.rc.gem b/vendor/cache/actionpack-3.0.0.rc.gem deleted file mode 100644 index 6fa843c..0000000 Binary files a/vendor/cache/actionpack-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/activemodel-3.0.0.gem b/vendor/cache/activemodel-3.0.0.gem new file mode 100644 index 0000000..c0a334f Binary files /dev/null and b/vendor/cache/activemodel-3.0.0.gem differ diff --git a/vendor/cache/activemodel-3.0.0.rc.gem b/vendor/cache/activemodel-3.0.0.rc.gem deleted file mode 100644 index 6ff7278..0000000 Binary files a/vendor/cache/activemodel-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/activerecord-3.0.0.gem b/vendor/cache/activerecord-3.0.0.gem new file mode 100644 index 0000000..620c19d Binary files /dev/null and b/vendor/cache/activerecord-3.0.0.gem differ diff --git a/vendor/cache/activerecord-3.0.0.rc.gem b/vendor/cache/activerecord-3.0.0.rc.gem deleted file mode 100644 index 4c03f3e..0000000 Binary files a/vendor/cache/activerecord-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/activeresource-3.0.0.gem b/vendor/cache/activeresource-3.0.0.gem new file mode 100644 index 0000000..9b25990 Binary files /dev/null and b/vendor/cache/activeresource-3.0.0.gem differ diff --git a/vendor/cache/activeresource-3.0.0.rc.gem b/vendor/cache/activeresource-3.0.0.rc.gem deleted file mode 100644 index 463cdfa..0000000 Binary files a/vendor/cache/activeresource-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/activesupport-3.0.0.gem b/vendor/cache/activesupport-3.0.0.gem new file mode 100644 index 0000000..0ab57b1 Binary files /dev/null and b/vendor/cache/activesupport-3.0.0.gem differ diff --git a/vendor/cache/activesupport-3.0.0.rc.gem b/vendor/cache/activesupport-3.0.0.rc.gem deleted file mode 100644 index 74c6d53..0000000 Binary files a/vendor/cache/activesupport-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/arel-0.4.0.gem b/vendor/cache/arel-0.4.0.gem deleted file mode 100644 index 9967cf7..0000000 Binary files a/vendor/cache/arel-0.4.0.gem and /dev/null differ diff --git a/vendor/cache/arel-1.0.1.gem b/vendor/cache/arel-1.0.1.gem new file mode 100644 index 0000000..a876978 Binary files /dev/null and b/vendor/cache/arel-1.0.1.gem differ diff --git a/vendor/cache/escape_utils-0.1.5.gem b/vendor/cache/escape_utils-0.1.5.gem new file mode 100644 index 0000000..3629e72 Binary files /dev/null and b/vendor/cache/escape_utils-0.1.5.gem differ diff --git a/vendor/cache/rack-mount-0.6.13.gem b/vendor/cache/rack-mount-0.6.13.gem new file mode 100644 index 0000000..ce90fe5 Binary files /dev/null and b/vendor/cache/rack-mount-0.6.13.gem differ diff --git a/vendor/cache/rack-mount-0.6.9.gem b/vendor/cache/rack-mount-0.6.9.gem deleted file mode 100644 index 178c280..0000000 Binary files a/vendor/cache/rack-mount-0.6.9.gem and /dev/null differ diff --git a/vendor/cache/rails-3.0.0.rc.gem b/vendor/cache/rails-3.0.0.gem similarity index 69% rename from vendor/cache/rails-3.0.0.rc.gem rename to vendor/cache/rails-3.0.0.gem index 3eb8b86..4ebe5f8 100644 Binary files a/vendor/cache/rails-3.0.0.rc.gem and b/vendor/cache/rails-3.0.0.gem differ diff --git a/vendor/cache/railties-3.0.0.gem b/vendor/cache/railties-3.0.0.gem new file mode 100644 index 0000000..de9b9bc Binary files /dev/null and b/vendor/cache/railties-3.0.0.gem differ diff --git a/vendor/cache/railties-3.0.0.rc.gem b/vendor/cache/railties-3.0.0.rc.gem deleted file mode 100644 index 1fdf5a4..0000000 Binary files a/vendor/cache/railties-3.0.0.rc.gem and /dev/null differ diff --git a/vendor/cache/tzinfo-0.3.22.gem b/vendor/cache/tzinfo-0.3.22.gem deleted file mode 100644 index 6499764..0000000 Binary files a/vendor/cache/tzinfo-0.3.22.gem and /dev/null differ diff --git a/vendor/cache/tzinfo-0.3.23.gem b/vendor/cache/tzinfo-0.3.23.gem new file mode 100644 index 0000000..df3a777 Binary files /dev/null and b/vendor/cache/tzinfo-0.3.23.gem differ
cincinnatirb/Suggestion-Box
0afe1d7dd7c0b8eba453d045e3609317be52e82a
Using Capybara for integration testing.
diff --git a/Gemfile b/Gemfile index 4b4c94c..7091e47 100644 --- a/Gemfile +++ b/Gemfile @@ -1,12 +1,14 @@ source :gemcutter gem "rails", "3.0.0.rc" gem "sqlite3-ruby", :require => "sqlite3" gem 'formtastic', :git => "http://github.com/justinfrench/formtastic.git", :branch => "rails3" +gem "escape_utils" group :test do gem "factory_girl_rails" gem "shoulda" gem "flexmock" - gem "webrat", "0.7.2.beta.1" + gem "capybara" + end diff --git a/Gemfile.lock b/Gemfile.lock index 90864d7..5a023b3 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,99 +1,113 @@ GIT remote: http://github.com/justinfrench/formtastic.git revision: 42b4eb8 branch: rails3 specs: formtastic (1.0.0) actionpack (>= 2.3.0) activesupport (>= 2.3.0) i18n (>= 0.4.0) GEM remote: http://rubygems.org/ specs: abstract (1.0.0) actionmailer (3.0.0.rc) actionpack (= 3.0.0.rc) mail (~> 2.2.5) actionpack (3.0.0.rc) activemodel (= 3.0.0.rc) activesupport (= 3.0.0.rc) builder (~> 2.1.2) erubis (~> 2.6.6) i18n (~> 0.4.1) rack (~> 1.2.1) rack-mount (~> 0.6.9) rack-test (~> 0.5.4) tzinfo (~> 0.3.22) activemodel (3.0.0.rc) activesupport (= 3.0.0.rc) builder (~> 2.1.2) i18n (~> 0.4.1) activerecord (3.0.0.rc) activemodel (= 3.0.0.rc) activesupport (= 3.0.0.rc) arel (~> 0.4.0) tzinfo (~> 0.3.22) activeresource (3.0.0.rc) activemodel (= 3.0.0.rc) activesupport (= 3.0.0.rc) activesupport (3.0.0.rc) arel (0.4.0) activesupport (>= 3.0.0.beta) builder (2.1.2) + capybara (0.3.9) + culerity (>= 0.2.4) + mime-types (>= 1.16) + nokogiri (>= 1.3.3) + rack (>= 1.0.0) + rack-test (>= 0.5.4) + selenium-webdriver (>= 0.0.3) + culerity (0.2.10) erubis (2.6.6) abstract (>= 1.0.0) + escape_utils (0.1.5) factory_girl (1.3.2) factory_girl_rails (1.0) factory_girl (~> 1.3) rails (>= 3.0.0.beta4) + ffi (0.6.3) + rake (>= 0.8.7) flexmock (0.8.7) i18n (0.4.1) + json_pure (1.4.6) mail (2.2.5) activesupport (>= 2.3.6) mime-types treetop (>= 1.4.5) mime-types (1.16) nokogiri (1.4.3.1) polyglot (0.3.1) rack (1.2.1) rack-mount (0.6.9) rack (>= 1.0.0) rack-test (0.5.4) rack (>= 1.0) rails (3.0.0.rc) actionmailer (= 3.0.0.rc) actionpack (= 3.0.0.rc) activerecord (= 3.0.0.rc) activeresource (= 3.0.0.rc) activesupport (= 3.0.0.rc) bundler (>= 1.0.0.rc.1) railties (= 3.0.0.rc) railties (3.0.0.rc) actionpack (= 3.0.0.rc) activesupport (= 3.0.0.rc) rake (>= 0.8.3) thor (~> 0.14.0) rake (0.8.7) + rubyzip (0.9.4) + selenium-webdriver (0.0.27) + ffi (>= 0.6.1) + json_pure + rubyzip shoulda (2.11.3) sqlite3-ruby (1.3.1) thor (0.14.0) treetop (1.4.8) polyglot (>= 0.3.1) tzinfo (0.3.22) - webrat (0.7.2.beta.1) - nokogiri (>= 1.2.0) - rack (>= 1.0) - rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES + capybara + escape_utils factory_girl_rails flexmock formtastic! rails (= 3.0.0.rc) shoulda sqlite3-ruby - webrat (= 0.7.2.beta.1) diff --git a/config/initializers/escape_utils.rb b/config/initializers/escape_utils.rb new file mode 100644 index 0000000..f017aa5 --- /dev/null +++ b/config/initializers/escape_utils.rb @@ -0,0 +1,7 @@ +module Rack + module Utils + def escape(s) + EscapeUtils.escape_url(s) + end + end +end diff --git a/test/factories.rb b/test/factories.rb index d1e6d45..8fad4fb 100644 --- a/test/factories.rb +++ b/test/factories.rb @@ -1,4 +1,9 @@ Factory.define(:topic) do |f| f.title "Title #{Time.now}" f.description "Some awesome topic that we'll discuss in depth" end + +# :complete_topic includes an entry for all available fields. +Factory.define(:complete_topic, :parent => 'topic') do |f| + f.suggestor "Bob" +end diff --git a/test/integration/creating_topics_test.rb b/test/integration/creating_topics_test.rb new file mode 100644 index 0000000..a477b7d --- /dev/null +++ b/test/integration/creating_topics_test.rb @@ -0,0 +1,40 @@ +require 'test_helper' + +class CreatingTopicsTest < ActionController::IntegrationTest + context "When visiting the new topic page" do + setup do + visit new_topic_path + end + + should "see 'New Topic'" do + assert page.has_content?('New Topic') + end + end + + context "After submitting a topic" do + setup do + @topic = Factory.build(:complete_topic) + + visit new_topic_path + fill_in 'Title', :with => @topic.title + fill_in 'Description', :with => @topic.description + fill_in 'Suggestor', :with => @topic.suggestor + click_button 'Create Topic' + end + + should "see the topics index page" do + assert (page.current_url == topics_url) + end + + should "see the new topic as a link" do + assert page.has_link?(@topic.title) + end + + should "see the title, description, and suggestor on the show topic page" do + click_link @topic.title + assert page.has_content?(@topic.title), "Should show the title" + assert page.has_content?(@topic.description), "Should show the description" + assert page.has_content?(@topic.suggestor), "Should show the suggestor" + end + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index ddbbb0f..a17f108 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,16 +1,18 @@ ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' +require 'capybara/rails' + +class ActionController::IntegrationTest + include Capybara +end class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... end - -require 'webrat' -Webrat.configure {|config| config.mode = :rack; config.open_error_files = false } diff --git a/vendor/cache/capybara-0.3.9.gem b/vendor/cache/capybara-0.3.9.gem new file mode 100644 index 0000000..8ee92a9 Binary files /dev/null and b/vendor/cache/capybara-0.3.9.gem differ diff --git a/vendor/cache/culerity-0.2.10.gem b/vendor/cache/culerity-0.2.10.gem new file mode 100644 index 0000000..e38d14a Binary files /dev/null and b/vendor/cache/culerity-0.2.10.gem differ diff --git a/vendor/cache/ffi-0.6.3.gem b/vendor/cache/ffi-0.6.3.gem new file mode 100644 index 0000000..42b92b8 Binary files /dev/null and b/vendor/cache/ffi-0.6.3.gem differ diff --git a/vendor/cache/json_pure-1.4.6.gem b/vendor/cache/json_pure-1.4.6.gem new file mode 100644 index 0000000..5abdc1b Binary files /dev/null and b/vendor/cache/json_pure-1.4.6.gem differ diff --git a/vendor/cache/rubyzip-0.9.4.gem b/vendor/cache/rubyzip-0.9.4.gem new file mode 100644 index 0000000..595e85a Binary files /dev/null and b/vendor/cache/rubyzip-0.9.4.gem differ diff --git a/vendor/cache/selenium-webdriver-0.0.27.gem b/vendor/cache/selenium-webdriver-0.0.27.gem new file mode 100644 index 0000000..d8e5a6a Binary files /dev/null and b/vendor/cache/selenium-webdriver-0.0.27.gem differ diff --git a/vendor/cache/webrat-0.7.2.beta.1.gem b/vendor/cache/webrat-0.7.2.beta.1.gem deleted file mode 100644 index fd5d4c8..0000000 Binary files a/vendor/cache/webrat-0.7.2.beta.1.gem and /dev/null differ
cincinnatirb/Suggestion-Box
49160e1ea366b5b416c108c40185326f00decb3e
generating formtastic stylesheets
diff --git a/config/initializers/formtastic.rb b/config/initializers/formtastic.rb new file mode 100644 index 0000000..bb710ef --- /dev/null +++ b/config/initializers/formtastic.rb @@ -0,0 +1,54 @@ +# Set the default text field size when input is a string. Default is 50. +# Formtastic::SemanticFormBuilder.default_text_field_size = 50 + +# Set the default text area height when input is a text. Default is 20. +# Formtastic::SemanticFormBuilder.default_text_area_height = 5 + +# Should all fields be considered "required" by default? +# Defaults to true, see ValidationReflection notes below. +# Formtastic::SemanticFormBuilder.all_fields_required_by_default = true + +# Should select fields have a blank option/prompt by default? +# Defaults to true. +# Formtastic::SemanticFormBuilder.include_blank_for_select_by_default = true + +# Set the string that will be appended to the labels/fieldsets which are required +# It accepts string or procs and the default is a localized version of +# '<abbr title="required">*</abbr>'. In other words, if you configure formtastic.required +# in your locale, it will replace the abbr title properly. But if you don't want to use +# abbr tag, you can simply give a string as below +# Formtastic::SemanticFormBuilder.required_string = "(required)" + +# Set the string that will be appended to the labels/fieldsets which are optional +# Defaults to an empty string ("") and also accepts procs (see required_string above) +# Formtastic::SemanticFormBuilder.optional_string = "(optional)" + +# Set the way inline errors will be displayed. +# Defaults to :sentence, valid options are :sentence, :list and :none +# Formtastic::SemanticFormBuilder.inline_errors = :sentence + +# Set the method to call on label text to transform or format it for human-friendly +# reading when formtastic is used without object. Defaults to :humanize. +# Formtastic::SemanticFormBuilder.label_str_method = :humanize + +# Set the array of methods to try calling on parent objects in :select and :radio inputs +# for the text inside each @<option>@ tag or alongside each radio @<input>@. The first method +# that is found on the object will be used. +# Defaults to ["to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"] +# Formtastic::SemanticFormBuilder.collection_label_methods = [ +# "to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"] + +# Formtastic by default renders inside li tags the input, hints and then +# errors messages. Sometimes you want the hints to be rendered first than +# the input, in the following order: hints, input and errors. You can +# customize it doing just as below: +# Formtastic::SemanticFormBuilder.inline_order = [:input, :hints, :errors] + +# Specifies if labels/hints for input fields automatically be looked up using I18n. +# Default value: false. Overridden for specific fields by setting value to true, +# i.e. :label => true, or :hint => true (or opposite depending on initialized value) +# Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false + +# You can add custom inputs or override parts of Formtastic by subclassing SemanticFormBuilder and +# specifying that class here. Defaults to SemanticFormBuilder. +# Formtastic::SemanticFormHelper.builder = MyCustomBuilder diff --git a/public/stylesheets/formtastic.css b/public/stylesheets/formtastic.css new file mode 100644 index 0000000..8051383 --- /dev/null +++ b/public/stylesheets/formtastic.css @@ -0,0 +1,131 @@ +/* ------------------------------------------------------------------------------------------------- + +It's *strongly* suggested that you don't modify this file. Instead, load a new stylesheet after +this one in your layouts (eg formtastic_changes.css) and override the styles to suit your needs. +This will allow you to update formtastic.css with new releases without clobbering your own changes. + +This stylesheet forms part of the Formtastic Rails Plugin +(c) 2008 Justin French + +--------------------------------------------------------------------------------------------------*/ + + +/* NORMALIZE AND RESET - obviously inspired by Yahoo's reset.css, but scoped to just form.formtastic +--------------------------------------------------------------------------------------------------*/ +form.formtastic, form.formtastic ul, form.formtastic ol, form.formtastic li, form.formtastic fieldset, form.formtastic legend, form.formtastic input, form.formtastic textarea, form.formtastic select, form.formtastic p { margin:0; padding:0; } +form.formtastic fieldset { border:0; } +form.formtastic em, form.formtastic strong { font-style:normal; font-weight:normal; } +form.formtastic ol, form.formtastic ul { list-style:none; } +form.formtastic abbr, form.formtastic acronym { border:0; font-variant:normal; } +form.formtastic input, form.formtastic textarea, form.formtastic select { font-family:inherit; font-size:inherit; font-weight:inherit; } +form.formtastic input, form.formtastic textarea, form.formtastic select { font-size:100%; } +form.formtastic legend { white-space:normal; color:#000; } + + +/* SEMANTIC ERRORS +--------------------------------------------------------------------------------------------------*/ +form.formtastic ul.errors { color:#cc0000; margin:0.5em 0 1.5em 25%; list-style:square; } +form.formtastic ul.errors li { padding:0; border:none; display:list-item; } + + +/* FIELDSETS & LISTS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset { overflow:auto; } /* clearing contained floats */ +form.formtastic fieldset.inputs { } +form.formtastic fieldset.buttons { padding-left:25%; } +form.formtastic fieldset ol { } +form.formtastic fieldset.buttons li { float:left; padding-right:0.5em; } + +/* INPUT LIs +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li { margin-bottom:1.5em; } +form.formtastic fieldset > ol > li { overflow:auto; } /* clearing contained floats */ + +form.formtastic fieldset > ol > li.required { } +form.formtastic fieldset > ol > li.optional { } +form.formtastic fieldset > ol > li.error { } + + +/* LABELS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li label { display:block; width:25%; float:left; padding-top:.2em; } +form.formtastic fieldset > ol > li > li label { line-height:100%; padding-top:0; } +form.formtastic fieldset > ol > li > li label input { line-height:100%; vertical-align:middle; margin-top:-0.1em;} + + +/* NESTED FIELDSETS AND LEGENDS (radio, check boxes and date/time inputs use nested fieldsets) +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li fieldset { position:relative; } +form.formtastic fieldset > ol > li fieldset legend { position:absolute; width:95%; padding-top:0.1em; left: 0px; } +form.formtastic fieldset > ol > li fieldset legend span { position:absolute; } +form.formtastic fieldset > ol > li fieldset legend.label label { position:absolute; } +form.formtastic fieldset > ol > li fieldset ol { float:left; width:74%; margin:0; padding:0 0 0 25%; } +form.formtastic fieldset > ol > li fieldset ol li { padding:0; border:0; } + + +/* INLINE HINTS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li p.inline-hints { color:#666; margin:0.5em 0 0 25%; } + + +/* INLINE ERRORS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li p.inline-errors { color:#cc0000; margin:0.5em 0 0 25%; } +form.formtastic fieldset > ol > li ul.errors { color:#cc0000; margin:0.5em 0 0 25%; list-style:square; } +form.formtastic fieldset > ol > li ul.errors li { padding:0; border:none; display:list-item; } + + +/* STRING & NUMERIC OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li.string input { max-width:74%; } +form.formtastic fieldset > ol > li.password input { max-width: 13em; } +form.formtastic fieldset > ol > li.numeric input { max-width:74%; } + + +/* TEXTAREA OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li.text textarea { width:74%; } + + +/* HIDDEN OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.hidden { display:none; } + +/* BOOLEAN OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li.boolean label { padding-left:25%; width:auto; } +form.formtastic fieldset > ol > li.boolean label input { margin:0 0.5em 0 0.2em; } + + +/* RADIO OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li.radio { } +form.formtastic fieldset > ol > li.radio fieldset ol { margin-bottom:-0.6em; } +form.formtastic fieldset > ol > li.radio fieldset ol li { margin:0.1em 0 0.5em 0; } +form.formtastic fieldset > ol > li.radio fieldset ol li label { float:none; width:100%; } +form.formtastic fieldset > ol > li.radio fieldset ol li label input { margin-right:0.2em; } + + +/* CHECK BOXES (COLLECTION) OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li.check_boxes { } +form.formtastic fieldset > ol > li.check_boxes fieldset ol { margin-bottom:-0.6em; } +form.formtastic fieldset > ol > li.check_boxes fieldset ol li { margin:0.1em 0 0.5em 0; } +form.formtastic fieldset > ol > li.check_boxes fieldset ol li label { float:none; width:100%; } +form.formtastic fieldset > ol > li.check_boxes fieldset ol li label input { margin-right:0.2em; } + + + +/* DATE & TIME OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset > ol > li.date fieldset ol li, +form.formtastic fieldset > ol > li.time fieldset ol li, +form.formtastic fieldset > ol > li.datetime fieldset ol li { float:left; width:auto; margin:0 .3em 0 0; } + +form.formtastic fieldset > ol > li.date fieldset ol li label, +form.formtastic fieldset > ol > li.time fieldset ol li label, +form.formtastic fieldset > ol > li.datetime fieldset ol li label { display:none; } + +form.formtastic fieldset > ol > li.date fieldset ol li label input, +form.formtastic fieldset > ol > li.time fieldset ol li label input, +form.formtastic fieldset > ol > li.datetime fieldset ol li label input { display:inline; margin:0; padding:0; } diff --git a/public/stylesheets/formtastic_changes.css b/public/stylesheets/formtastic_changes.css new file mode 100644 index 0000000..8a044fa --- /dev/null +++ b/public/stylesheets/formtastic_changes.css @@ -0,0 +1,14 @@ +/* ------------------------------------------------------------------------------------------------- + +Load this stylesheet after formtastic.css in your layouts to override the CSS to suit your needs. +This will allow you to update formtastic.css with new releases without clobbering your own changes. + +For example, to make the inline hint paragraphs a little darker in color than the standard #666: + +form.formtastic fieldset > ol > li p.inline-hints { color:#333; } + +HINT: +The following style may be *conditionally* included for improved support on older versions of IE(<8) +form.formtastic fieldset ol li fieldset legend { margin-left: -6px;} + +--------------------------------------------------------------------------------------------------*/
cincinnatirb/Suggestion-Box
63cd15359490dbe7e5f5f11999aa44d6e2e139e4
add ability to show a topic (aka, a suggestion)
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb index 2142098..4be8cf1 100644 --- a/app/controllers/topics_controller.rb +++ b/app/controllers/topics_controller.rb @@ -1,18 +1,22 @@ class TopicsController < ApplicationController def index @topics = Topic.all end + def show + @topic = Topic.find(params[:id]) + end + def new @topic = Topic.new end def create if @topic = Topic.create(params[:topic]) redirect_to topics_path else render :new end end end diff --git a/app/views/topics/show.html.erb b/app/views/topics/show.html.erb new file mode 100644 index 0000000..0df4c3b --- /dev/null +++ b/app/views/topics/show.html.erb @@ -0,0 +1,10 @@ +<h1><%= @topic.title %></h1> +<h2>By <%= @topic.suggestor %> </h2> +<p><em><%= time_ago_in_words(@topic.created_at) %> ago</em></p> + +<p><%= @topic.description %></p> + +<p> +<%= link_to 'Back to list', topics_path %> | +<%= link_to 'Suggest Something', new_topic_path %> +</p> diff --git a/test/functional/topics_controller_test.rb b/test/functional/topics_controller_test.rb index d46373a..f09e284 100644 --- a/test/functional/topics_controller_test.rb +++ b/test/functional/topics_controller_test.rb @@ -1,30 +1,38 @@ require 'test_helper' class TopicsControllerTest < ActionController::TestCase context "new topic" do setup do get :new end should respond_with(:success) end context "creating a topic" do setup do @topic_count = Topic.count post :create, :topic => { :title => "Some New Topic", :description => ""} end should redirect_to("list of topics") { topics_path } should "increase the number of topics" do assert Topic.count > @topic_count, "#{Topic.count} is not greater than #{@topic_count}" end end context "list of topics" do setup do Factory(:topic) get :index end should respond_with(:success) end + + context "seeing one topic" do + setup do + @topic = Factory(:topic) + get :show, :id => @topic.id.to_s + end + should respond_with(:success) + end end
cincinnatirb/Suggestion-Box
b9519e6c97178b20bc096d9d82330f5e17d0305d
Fancy up the home page with a "no topics yet" message.
diff --git a/app/views/topics/index.html.erb b/app/views/topics/index.html.erb index 8582d35..d1a194d 100644 --- a/app/views/topics/index.html.erb +++ b/app/views/topics/index.html.erb @@ -1,8 +1,13 @@ -<h1>Topics</h1> -<ul> - <%= render @topics %> -</ul> +<h2>Suggestion Box</h2> -<p> - <%= link_to "Submit a new Topic", new_topic_path %> -</p> +<p>List of topics submitted so far:</p> + +<% if @topics.blank? %> + <p>No topics submitted so far. Do you have any suggestions?</p> +<% else %> + <ul> + <%= render @topics %> + </ul> +<% end %> + +<p><%= link_to "Suggest Something", new_topic_path %></p>
cincinnatirb/Suggestion-Box
0cecf7fb2d6f902e46fbfe2fd1589c5660b0987a
Add vendor/cache to source control so bundle install will install from there in prod.
diff --git a/vendor/cache/abstract-1.0.0.gem b/vendor/cache/abstract-1.0.0.gem new file mode 100644 index 0000000..a9be232 Binary files /dev/null and b/vendor/cache/abstract-1.0.0.gem differ diff --git a/vendor/cache/actionmailer-3.0.0.rc.gem b/vendor/cache/actionmailer-3.0.0.rc.gem new file mode 100644 index 0000000..b6dc177 Binary files /dev/null and b/vendor/cache/actionmailer-3.0.0.rc.gem differ diff --git a/vendor/cache/actionpack-3.0.0.rc.gem b/vendor/cache/actionpack-3.0.0.rc.gem new file mode 100644 index 0000000..6fa843c Binary files /dev/null and b/vendor/cache/actionpack-3.0.0.rc.gem differ diff --git a/vendor/cache/activemodel-3.0.0.rc.gem b/vendor/cache/activemodel-3.0.0.rc.gem new file mode 100644 index 0000000..6ff7278 Binary files /dev/null and b/vendor/cache/activemodel-3.0.0.rc.gem differ diff --git a/vendor/cache/activerecord-3.0.0.rc.gem b/vendor/cache/activerecord-3.0.0.rc.gem new file mode 100644 index 0000000..4c03f3e Binary files /dev/null and b/vendor/cache/activerecord-3.0.0.rc.gem differ diff --git a/vendor/cache/activeresource-3.0.0.rc.gem b/vendor/cache/activeresource-3.0.0.rc.gem new file mode 100644 index 0000000..463cdfa Binary files /dev/null and b/vendor/cache/activeresource-3.0.0.rc.gem differ diff --git a/vendor/cache/activesupport-3.0.0.rc.gem b/vendor/cache/activesupport-3.0.0.rc.gem new file mode 100644 index 0000000..74c6d53 Binary files /dev/null and b/vendor/cache/activesupport-3.0.0.rc.gem differ diff --git a/vendor/cache/arel-0.4.0.gem b/vendor/cache/arel-0.4.0.gem new file mode 100644 index 0000000..9967cf7 Binary files /dev/null and b/vendor/cache/arel-0.4.0.gem differ diff --git a/vendor/cache/builder-2.1.2.gem b/vendor/cache/builder-2.1.2.gem new file mode 100644 index 0000000..c901697 Binary files /dev/null and b/vendor/cache/builder-2.1.2.gem differ diff --git a/vendor/cache/erubis-2.6.6.gem b/vendor/cache/erubis-2.6.6.gem new file mode 100644 index 0000000..17b23c4 Binary files /dev/null and b/vendor/cache/erubis-2.6.6.gem differ diff --git a/vendor/cache/factory_girl-1.3.2.gem b/vendor/cache/factory_girl-1.3.2.gem new file mode 100644 index 0000000..7c7a7da Binary files /dev/null and b/vendor/cache/factory_girl-1.3.2.gem differ diff --git a/vendor/cache/factory_girl_rails-1.0.gem b/vendor/cache/factory_girl_rails-1.0.gem new file mode 100644 index 0000000..cabd7b1 Binary files /dev/null and b/vendor/cache/factory_girl_rails-1.0.gem differ diff --git a/vendor/cache/flexmock-0.8.7.gem b/vendor/cache/flexmock-0.8.7.gem new file mode 100644 index 0000000..58ac1e3 Binary files /dev/null and b/vendor/cache/flexmock-0.8.7.gem differ diff --git a/vendor/cache/i18n-0.4.1.gem b/vendor/cache/i18n-0.4.1.gem new file mode 100644 index 0000000..86714c8 Binary files /dev/null and b/vendor/cache/i18n-0.4.1.gem differ diff --git a/vendor/cache/mail-2.2.5.gem b/vendor/cache/mail-2.2.5.gem new file mode 100644 index 0000000..c65e21c Binary files /dev/null and b/vendor/cache/mail-2.2.5.gem differ diff --git a/vendor/cache/mime-types-1.16.gem b/vendor/cache/mime-types-1.16.gem new file mode 100644 index 0000000..49f1ef2 Binary files /dev/null and b/vendor/cache/mime-types-1.16.gem differ diff --git a/vendor/cache/nokogiri-1.4.3.1.gem b/vendor/cache/nokogiri-1.4.3.1.gem new file mode 100644 index 0000000..72db701 Binary files /dev/null and b/vendor/cache/nokogiri-1.4.3.1.gem differ diff --git a/vendor/cache/polyglot-0.3.1.gem b/vendor/cache/polyglot-0.3.1.gem new file mode 100644 index 0000000..9bdd037 Binary files /dev/null and b/vendor/cache/polyglot-0.3.1.gem differ diff --git a/vendor/cache/rack-1.2.1.gem b/vendor/cache/rack-1.2.1.gem new file mode 100644 index 0000000..6a594a8 Binary files /dev/null and b/vendor/cache/rack-1.2.1.gem differ diff --git a/vendor/cache/rack-mount-0.6.10.gem b/vendor/cache/rack-mount-0.6.10.gem new file mode 100644 index 0000000..3770956 Binary files /dev/null and b/vendor/cache/rack-mount-0.6.10.gem differ diff --git a/vendor/cache/rack-test-0.5.4.gem b/vendor/cache/rack-test-0.5.4.gem new file mode 100644 index 0000000..f237608 Binary files /dev/null and b/vendor/cache/rack-test-0.5.4.gem differ diff --git a/vendor/cache/rails-3.0.0.rc.gem b/vendor/cache/rails-3.0.0.rc.gem new file mode 100644 index 0000000..3eb8b86 Binary files /dev/null and b/vendor/cache/rails-3.0.0.rc.gem differ diff --git a/vendor/cache/railties-3.0.0.rc.gem b/vendor/cache/railties-3.0.0.rc.gem new file mode 100644 index 0000000..1fdf5a4 Binary files /dev/null and b/vendor/cache/railties-3.0.0.rc.gem differ diff --git a/vendor/cache/rake-0.8.7.gem b/vendor/cache/rake-0.8.7.gem new file mode 100644 index 0000000..0740cec Binary files /dev/null and b/vendor/cache/rake-0.8.7.gem differ diff --git a/vendor/cache/shoulda-2.11.3.gem b/vendor/cache/shoulda-2.11.3.gem new file mode 100644 index 0000000..549488f Binary files /dev/null and b/vendor/cache/shoulda-2.11.3.gem differ diff --git a/vendor/cache/sqlite3-ruby-1.3.1.gem b/vendor/cache/sqlite3-ruby-1.3.1.gem new file mode 100644 index 0000000..897d7ca Binary files /dev/null and b/vendor/cache/sqlite3-ruby-1.3.1.gem differ diff --git a/vendor/cache/thor-0.14.0.gem b/vendor/cache/thor-0.14.0.gem new file mode 100644 index 0000000..b464f83 Binary files /dev/null and b/vendor/cache/thor-0.14.0.gem differ diff --git a/vendor/cache/treetop-1.4.8.gem b/vendor/cache/treetop-1.4.8.gem new file mode 100644 index 0000000..22b4973 Binary files /dev/null and b/vendor/cache/treetop-1.4.8.gem differ diff --git a/vendor/cache/tzinfo-0.3.23.gem b/vendor/cache/tzinfo-0.3.23.gem new file mode 100644 index 0000000..df3a777 Binary files /dev/null and b/vendor/cache/tzinfo-0.3.23.gem differ diff --git a/vendor/cache/webrat-0.7.2.beta.1.gem b/vendor/cache/webrat-0.7.2.beta.1.gem new file mode 100644 index 0000000..fd5d4c8 Binary files /dev/null and b/vendor/cache/webrat-0.7.2.beta.1.gem differ
cincinnatirb/Suggestion-Box
d457eb70484c97a88cd05c797dff9a8584dc4e10
converting "==" heading markers to working markdown headers
diff --git a/README.md b/README.md index 1016d5a..3d4bb4e 100644 --- a/README.md +++ b/README.md @@ -1,306 +1,306 @@ -== Welcome to the Cincinnati Ruby Brigade's Suggestion Box +# Welcome to the Cincinnati Ruby Brigade's Suggestion Box This app started as a demo project for the Cinci.rb group to work on together. It's serving several purposes. First, as an app for the newer rubyists in the group to get their feet wet with a rails app. Second, it serves as a test-bed for demonstrating and experimenting new gems. Finally, cinci.rb actually needs a suggestion box for new meeting topics as an effort to get the group as a whole more involved in the planning of our meetings. -== Getting Started +## Getting Started You'll need to start with: * rvm link:http://rvm.beginrescueend.com/ ** <tt>gem install rvm</tt> * (for Windows users) ** pik link:http://github.com/vertiginous/pik ** <tt>gem install pik</tt> * ruby-1.9.2-rc2 (rvm install ruby-1.9.2-rc2) * sqlite3 3.6+ link:http://www.sqlite.org/download.html ** Mac OS X has sqlite3, but Leopard's is too old * bundler link:http://gembundler.com/v1.0/index.html ** <tt>gem install bundler --pre</tt> After you get this project, you can just run: <tt>bundle install</tt> to get everything else. Then get your database ready and run the tests: <tt>rake db:migrate test</tt> And you can start a local server: <tt>rails server</tt> (which will be "rails s" from now on) And visit: http://localhost:3000/ The original Rails page is at: http://localhost:3000/rails Or jump right to the "about" info: http://localhost:3000/rails/info/properties The live site is running at: http://severe-autumn-80.heroku.com/ (But you might have to go to http://severe-autumn-80.heroku.com/topics or http://severe-autumn-80.heroku.com/topics/new for a bit.) -== Welcome to Rails +## Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. -== Getting Started +## Getting Started 1. At the command prompt, create a new Rails application: <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name) 2. Change directory to <tt>myapp</tt> and start the web server: <tt>cd myapp; rails server</tt> (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ -== Debugging Rails +## Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. -== Debugger +## Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example: class WeblogController < ActionController::Base def index @posts = Post.find(:all) debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#<Post:0x14a6be8 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>, #<Post:0x14a6620 @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". -== Console +## Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run <tt>rails console</tt> from the application directory. Options: * Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: <tt>rails console production</tt>. To reload your controllers and models after launching the console run <tt>reload!</tt> More information about irb can be found at: link:http://www.rubycentral.com/pickaxe/irb.html -== dbconsole +## dbconsole You can go to the command line of your database directly through <tt>rails dbconsole</tt>. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>rails dbconsole production</tt>. Currently works for MySQL, PostgreSQL and SQLite 3. -== Description of Contents +## Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers | |-- helpers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | `-- tasks |-- log |-- public | |-- images | |-- javascripts | `-- stylesheets |-- script | `-- performance |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | |-- cache | |-- pids | |-- sessions | `-- sockets `-- vendor `-- plugins app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using <tt>rake doc:app</tt> lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path.
cincinnatirb/Suggestion-Box
ed3402e558ce9e8ad3ac3fefb718e6414ba1b27f
Adding some description of what the project is about
diff --git a/README.md b/README.md index c55b7b5..1016d5a 100644 --- a/README.md +++ b/README.md @@ -1,296 +1,306 @@ == Welcome to the Cincinnati Ruby Brigade's Suggestion Box +This app started as a demo project for the Cinci.rb group to work on +together. It's serving several purposes. First, as an app for the +newer rubyists in the group to get their feet wet with a rails +app. Second, it serves as a test-bed for demonstrating and +experimenting new gems. Finally, cinci.rb actually needs a suggestion +box for new meeting topics as an effort to get the group as a whole +more involved in the planning of our meetings. + +== Getting Started + You'll need to start with: * rvm link:http://rvm.beginrescueend.com/ ** <tt>gem install rvm</tt> * (for Windows users) ** pik link:http://github.com/vertiginous/pik ** <tt>gem install pik</tt> * ruby-1.9.2-rc2 (rvm install ruby-1.9.2-rc2) * sqlite3 3.6+ link:http://www.sqlite.org/download.html ** Mac OS X has sqlite3, but Leopard's is too old * bundler link:http://gembundler.com/v1.0/index.html ** <tt>gem install bundler --pre</tt> After you get this project, you can just run: <tt>bundle install</tt> to get everything else. Then get your database ready and run the tests: <tt>rake db:migrate test</tt> And you can start a local server: <tt>rails server</tt> (which will be "rails s" from now on) And visit: http://localhost:3000/ The original Rails page is at: http://localhost:3000/rails Or jump right to the "about" info: http://localhost:3000/rails/info/properties The live site is running at: http://severe-autumn-80.heroku.com/ (But you might have to go to http://severe-autumn-80.heroku.com/topics or http://severe-autumn-80.heroku.com/topics/new for a bit.) == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, create a new Rails application: <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name) 2. Change directory to <tt>myapp</tt> and start the web server: <tt>cd myapp; rails server</tt> (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example: class WeblogController < ActionController::Base def index @posts = Post.find(:all) debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#<Post:0x14a6be8 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>, #<Post:0x14a6620 @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". == Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run <tt>rails console</tt> from the application directory. Options: * Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: <tt>rails console production</tt>. To reload your controllers and models after launching the console run <tt>reload!</tt> More information about irb can be found at: link:http://www.rubycentral.com/pickaxe/irb.html == dbconsole You can go to the command line of your database directly through <tt>rails dbconsole</tt>. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>rails dbconsole production</tt>. Currently works for MySQL, PostgreSQL and SQLite 3. == Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers | |-- helpers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | `-- tasks |-- log |-- public | |-- images | |-- javascripts | `-- stylesheets |-- script | `-- performance |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | |-- cache | |-- pids | |-- sessions | `-- sockets `-- vendor `-- plugins app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using <tt>rake doc:app</tt> lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path.
cincinnatirb/Suggestion-Box
6de1b087f22681270876fb5ae8ccf0ff119d592b
Move public/index.html to public/rails.html and update README
diff --git a/README b/README index edeee84..c55b7b5 100644 --- a/README +++ b/README @@ -1,290 +1,296 @@ == Welcome to the Cincinnati Ruby Brigade's Suggestion Box You'll need to start with: * rvm link:http://rvm.beginrescueend.com/ ** <tt>gem install rvm</tt> * (for Windows users) ** pik link:http://github.com/vertiginous/pik ** <tt>gem install pik</tt> * ruby-1.9.2-rc2 (rvm install ruby-1.9.2-rc2) * sqlite3 3.6+ link:http://www.sqlite.org/download.html ** Mac OS X has sqlite3, but Leopard's is too old * bundler link:http://gembundler.com/v1.0/index.html ** <tt>gem install bundler --pre</tt> After you get this project, you can just run: <tt>bundle install</tt> to get everything else. Then get your database ready and run the tests: <tt>rake db:migrate test</tt> And you can start a local server: <tt>rails server</tt> (which will be "rails s" from now on) -And visit link:http://localhost:3000/ +And visit: http://localhost:3000/ + +The original Rails page is at: http://localhost:3000/rails + +Or jump right to the "about" info: http://localhost:3000/rails/info/properties The live site is running at: http://severe-autumn-80.heroku.com/ +(But you might have to go to http://severe-autumn-80.heroku.com/topics or +http://severe-autumn-80.heroku.com/topics/new for a bit.) == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, create a new Rails application: <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name) 2. Change directory to <tt>myapp</tt> and start the web server: <tt>cd myapp; rails server</tt> (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example: class WeblogController < ActionController::Base def index @posts = Post.find(:all) debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#<Post:0x14a6be8 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>, #<Post:0x14a6620 @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". == Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run <tt>rails console</tt> from the application directory. Options: * Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: <tt>rails console production</tt>. To reload your controllers and models after launching the console run <tt>reload!</tt> More information about irb can be found at: link:http://www.rubycentral.com/pickaxe/irb.html == dbconsole You can go to the command line of your database directly through <tt>rails dbconsole</tt>. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>rails dbconsole production</tt>. Currently works for MySQL, PostgreSQL and SQLite 3. == Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers | |-- helpers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | `-- tasks |-- log |-- public | |-- images | |-- javascripts | `-- stylesheets |-- script | `-- performance |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | |-- cache | |-- pids | |-- sessions | `-- sockets `-- vendor `-- plugins app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using <tt>rake doc:app</tt> lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. diff --git a/public/index.html b/public/rails.html similarity index 100% rename from public/index.html rename to public/rails.html
cincinnatirb/Suggestion-Box
de9fbe90e273bdee6d1d6f0ee2051f1740312620
better README and some typical links
diff --git a/README b/README index 6966fe9..edeee84 100644 --- a/README +++ b/README @@ -1,256 +1,290 @@ +== Welcome to the Cincinnati Ruby Brigade's Suggestion Box + +You'll need to start with: + +* rvm link:http://rvm.beginrescueend.com/ +** <tt>gem install rvm</tt> +* (for Windows users) +** pik link:http://github.com/vertiginous/pik +** <tt>gem install pik</tt> +* ruby-1.9.2-rc2 (rvm install ruby-1.9.2-rc2) +* sqlite3 3.6+ link:http://www.sqlite.org/download.html +** Mac OS X has sqlite3, but Leopard's is too old +* bundler link:http://gembundler.com/v1.0/index.html +** <tt>gem install bundler --pre</tt> + +After you get this project, you can just run: + +<tt>bundle install</tt> + +to get everything else. Then get your database ready and run the tests: + +<tt>rake db:migrate test</tt> + +And you can start a local server: + +<tt>rails server</tt> (which will be "rails s" from now on) + +And visit link:http://localhost:3000/ + +The live site is running at: + +http://severe-autumn-80.heroku.com/ + + == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, create a new Rails application: <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name) 2. Change directory to <tt>myapp</tt> and start the web server: <tt>cd myapp; rails server</tt> (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example: class WeblogController < ActionController::Base def index @posts = Post.find(:all) debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#<Post:0x14a6be8 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>, #<Post:0x14a6620 @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". == Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run <tt>rails console</tt> from the application directory. Options: * Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: <tt>rails console production</tt>. To reload your controllers and models after launching the console run <tt>reload!</tt> More information about irb can be found at: link:http://www.rubycentral.com/pickaxe/irb.html == dbconsole You can go to the command line of your database directly through <tt>rails dbconsole</tt>. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like <tt>rails dbconsole production</tt>. Currently works for MySQL, PostgreSQL and SQLite 3. == Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers | |-- helpers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | `-- tasks |-- log |-- public | |-- images | |-- javascripts | `-- stylesheets |-- script | `-- performance |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | |-- cache | |-- pids | |-- sessions | `-- sockets `-- vendor `-- plugins app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using <tt>rake doc:app</tt> lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index c360f17..45d46e9 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,15 +1,15 @@ <!DOCTYPE html> <html> <head> - <title>SuggestionBox</title> + <title>Cincinnati.rb Suggestion Box</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> <%= formtastic_stylesheet_link_tag %> </head> <body> <%= yield %> </body> </html> diff --git a/app/views/topics/index.html.erb b/app/views/topics/index.html.erb index 4fd7e2f..8582d35 100644 --- a/app/views/topics/index.html.erb +++ b/app/views/topics/index.html.erb @@ -1,4 +1,8 @@ <h1>Topics</h1> <ul> <%= render @topics %> </ul> + +<p> + <%= link_to "Submit a new Topic", new_topic_path %> +</p> diff --git a/app/views/topics/new.html.erb b/app/views/topics/new.html.erb index 0849256..25317f6 100644 --- a/app/views/topics/new.html.erb +++ b/app/views/topics/new.html.erb @@ -1,6 +1,10 @@ <h1>New Topic</h1> <%= semantic_form_for @topic do |form| %> <%= form.inputs %> <%= form.buttons %> <% end %> + +<p> + <%= link_to 'Cancel', topics_path %> +</p> diff --git a/config/routes.rb b/config/routes.rb index 61595d4..ebd2f39 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,60 +1,61 @@ SuggestionBox::Application.routes.draw do + root :to => 'topics#index' resources :topics # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get :short # post :toggle # end # # collection do # get :sold # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get :recent, :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => "welcome#index" # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id(.:format)))' end
cincinnatirb/Suggestion-Box
8b93a70c23aa0b369d35a06b1b388b71c108c184
resolve deprecation warnings
diff --git a/app/views/topics/_topic.html.erb b/app/views/topics/_topic.html.erb index 188a076..5b93563 100644 --- a/app/views/topics/_topic.html.erb +++ b/app/views/topics/_topic.html.erb @@ -1 +1 @@ -<li><%= link_to topic.title %></li> + <li><%= link_to topic.title, topic %></li> diff --git a/app/views/topics/index.html.erb b/app/views/topics/index.html.erb index 88b534a..4fd7e2f 100644 --- a/app/views/topics/index.html.erb +++ b/app/views/topics/index.html.erb @@ -1,3 +1,4 @@ +<h1>Topics</h1> <ul> -<%= render @topics %> + <%= render @topics %> </ul> diff --git a/app/views/topics/new.html.erb b/app/views/topics/new.html.erb index ad03928..0849256 100644 --- a/app/views/topics/new.html.erb +++ b/app/views/topics/new.html.erb @@ -1,6 +1,6 @@ <h1>New Topic</h1> -<% semantic_form_for @topic do |form| %> +<%= semantic_form_for @topic do |form| %> <%= form.inputs %> <%= form.buttons %> <% end %> diff --git a/test/functional/topics_controller_test.rb b/test/functional/topics_controller_test.rb index f0e2ce9..d46373a 100644 --- a/test/functional/topics_controller_test.rb +++ b/test/functional/topics_controller_test.rb @@ -1,30 +1,30 @@ require 'test_helper' class TopicsControllerTest < ActionController::TestCase context "new topic" do setup do get :new end - should_respond_with :success + should respond_with(:success) end context "creating a topic" do setup do @topic_count = Topic.count post :create, :topic => { :title => "Some New Topic", :description => ""} end - should_redirect_to("list of topics") { topics_path } + should redirect_to("list of topics") { topics_path } should "increase the number of topics" do assert Topic.count > @topic_count, "#{Topic.count} is not greater than #{@topic_count}" end end context "list of topics" do setup do Factory(:topic) get :index end - should_respond_with :success + should respond_with(:success) end end
cincinnatirb/Suggestion-Box
2422c68dcbd68b5458e655945d2963ef8b5b311e
initial code to allow adding topics from web
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb new file mode 100644 index 0000000..2142098 --- /dev/null +++ b/app/controllers/topics_controller.rb @@ -0,0 +1,18 @@ +class TopicsController < ApplicationController + + def index + @topics = Topic.all + end + + def new + @topic = Topic.new + end + + def create + if @topic = Topic.create(params[:topic]) + redirect_to topics_path + else + render :new + end + end +end diff --git a/app/helpers/topics_helper.rb b/app/helpers/topics_helper.rb new file mode 100644 index 0000000..488eed5 --- /dev/null +++ b/app/helpers/topics_helper.rb @@ -0,0 +1,2 @@ +module TopicsHelper +end diff --git a/app/models/topic.rb b/app/models/topic.rb new file mode 100644 index 0000000..bcbb719 --- /dev/null +++ b/app/models/topic.rb @@ -0,0 +1,2 @@ +class Topic < ActiveRecord::Base +end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 0a3bce3..c360f17 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,14 +1,15 @@ <!DOCTYPE html> <html> <head> <title>SuggestionBox</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> + <%= formtastic_stylesheet_link_tag %> </head> <body> <%= yield %> </body> </html> diff --git a/app/views/topics/_topic.html.erb b/app/views/topics/_topic.html.erb new file mode 100644 index 0000000..188a076 --- /dev/null +++ b/app/views/topics/_topic.html.erb @@ -0,0 +1 @@ +<li><%= link_to topic.title %></li> diff --git a/app/views/topics/index.html.erb b/app/views/topics/index.html.erb new file mode 100644 index 0000000..88b534a --- /dev/null +++ b/app/views/topics/index.html.erb @@ -0,0 +1,3 @@ +<ul> +<%= render @topics %> +</ul> diff --git a/app/views/topics/new.html.erb b/app/views/topics/new.html.erb new file mode 100644 index 0000000..ad03928 --- /dev/null +++ b/app/views/topics/new.html.erb @@ -0,0 +1,6 @@ +<h1>New Topic</h1> + +<% semantic_form_for @topic do |form| %> + <%= form.inputs %> + <%= form.buttons %> +<% end %> diff --git a/config/routes.rb b/config/routes.rb index da2fc5a..61595d4 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,60 @@ SuggestionBox::Application.routes.draw do + resources :topics + # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get :short # post :toggle # end # # collection do # get :sold # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get :recent, :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => "welcome#index" # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id(.:format)))' end diff --git a/db/migrate/20100817233813_create_topics.rb b/db/migrate/20100817233813_create_topics.rb new file mode 100644 index 0000000..4bef674 --- /dev/null +++ b/db/migrate/20100817233813_create_topics.rb @@ -0,0 +1,15 @@ +class CreateTopics < ActiveRecord::Migration + def self.up + create_table :topics do |t| + t.string :title + t.text :description + t.string :suggestor + + t.timestamps + end + end + + def self.down + drop_table :topics + end +end diff --git a/test/factories.rb b/test/factories.rb new file mode 100644 index 0000000..d1e6d45 --- /dev/null +++ b/test/factories.rb @@ -0,0 +1,4 @@ +Factory.define(:topic) do |f| + f.title "Title #{Time.now}" + f.description "Some awesome topic that we'll discuss in depth" +end diff --git a/test/functional/topics_controller_test.rb b/test/functional/topics_controller_test.rb new file mode 100644 index 0000000..f0e2ce9 --- /dev/null +++ b/test/functional/topics_controller_test.rb @@ -0,0 +1,30 @@ +require 'test_helper' + +class TopicsControllerTest < ActionController::TestCase + + context "new topic" do + setup do + get :new + end + should_respond_with :success + end + + context "creating a topic" do + setup do + @topic_count = Topic.count + post :create, :topic => { :title => "Some New Topic", :description => ""} + end + should_redirect_to("list of topics") { topics_path } + should "increase the number of topics" do + assert Topic.count > @topic_count, "#{Topic.count} is not greater than #{@topic_count}" + end + end + + context "list of topics" do + setup do + Factory(:topic) + get :index + end + should_respond_with :success + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index 8bf1192..ddbbb0f 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,13 +1,16 @@ ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... end + +require 'webrat' +Webrat.configure {|config| config.mode = :rack; config.open_error_files = false } diff --git a/test/unit/helpers/topics_helper_test.rb b/test/unit/helpers/topics_helper_test.rb new file mode 100644 index 0000000..12cc0b4 --- /dev/null +++ b/test/unit/helpers/topics_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class TopicsHelperTest < ActionView::TestCase +end diff --git a/test/unit/topic_test.rb b/test/unit/topic_test.rb new file mode 100644 index 0000000..f6de4e8 --- /dev/null +++ b/test/unit/topic_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class TopicTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
cincinnatirb/Suggestion-Box
c2ddfe5baedc477602aef68794e7f469c9991f69
adding formtastic and factory_girl_rails gems and other test gems
diff --git a/Gemfile b/Gemfile index 8a03710..4b4c94c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,4 +1,12 @@ source :gemcutter gem "rails", "3.0.0.rc" gem "sqlite3-ruby", :require => "sqlite3" +gem 'formtastic', :git => "http://github.com/justinfrench/formtastic.git", :branch => "rails3" + +group :test do + gem "factory_girl_rails" + gem "shoulda" + gem "flexmock" + gem "webrat", "0.7.2.beta.1" +end diff --git a/Gemfile.lock b/Gemfile.lock index c0e7e37..90864d7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,73 +1,99 @@ +GIT + remote: http://github.com/justinfrench/formtastic.git + revision: 42b4eb8 + branch: rails3 + specs: + formtastic (1.0.0) + actionpack (>= 2.3.0) + activesupport (>= 2.3.0) + i18n (>= 0.4.0) + GEM remote: http://rubygems.org/ specs: abstract (1.0.0) actionmailer (3.0.0.rc) actionpack (= 3.0.0.rc) mail (~> 2.2.5) actionpack (3.0.0.rc) activemodel (= 3.0.0.rc) activesupport (= 3.0.0.rc) builder (~> 2.1.2) erubis (~> 2.6.6) i18n (~> 0.4.1) rack (~> 1.2.1) rack-mount (~> 0.6.9) rack-test (~> 0.5.4) tzinfo (~> 0.3.22) activemodel (3.0.0.rc) activesupport (= 3.0.0.rc) builder (~> 2.1.2) i18n (~> 0.4.1) activerecord (3.0.0.rc) activemodel (= 3.0.0.rc) activesupport (= 3.0.0.rc) arel (~> 0.4.0) tzinfo (~> 0.3.22) activeresource (3.0.0.rc) activemodel (= 3.0.0.rc) activesupport (= 3.0.0.rc) activesupport (3.0.0.rc) arel (0.4.0) activesupport (>= 3.0.0.beta) builder (2.1.2) erubis (2.6.6) abstract (>= 1.0.0) + factory_girl (1.3.2) + factory_girl_rails (1.0) + factory_girl (~> 1.3) + rails (>= 3.0.0.beta4) + flexmock (0.8.7) i18n (0.4.1) mail (2.2.5) activesupport (>= 2.3.6) mime-types treetop (>= 1.4.5) mime-types (1.16) + nokogiri (1.4.3.1) polyglot (0.3.1) rack (1.2.1) rack-mount (0.6.9) rack (>= 1.0.0) rack-test (0.5.4) rack (>= 1.0) rails (3.0.0.rc) actionmailer (= 3.0.0.rc) actionpack (= 3.0.0.rc) activerecord (= 3.0.0.rc) activeresource (= 3.0.0.rc) activesupport (= 3.0.0.rc) bundler (>= 1.0.0.rc.1) railties (= 3.0.0.rc) railties (3.0.0.rc) actionpack (= 3.0.0.rc) activesupport (= 3.0.0.rc) rake (>= 0.8.3) thor (~> 0.14.0) rake (0.8.7) + shoulda (2.11.3) sqlite3-ruby (1.3.1) thor (0.14.0) treetop (1.4.8) polyglot (>= 0.3.1) tzinfo (0.3.22) + webrat (0.7.2.beta.1) + nokogiri (>= 1.2.0) + rack (>= 1.0) + rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES + factory_girl_rails + flexmock + formtastic! rails (= 3.0.0.rc) + shoulda sqlite3-ruby + webrat (= 0.7.2.beta.1)
sophacles/vim-bundle-python
8f661092e2f79bfbdf4de76e8a490ec37e12c4cb
adding latest python.vim from vimscripts
diff --git a/ftplugin/python.vim b/ftplugin/python.vim index 7c7cf21..e2eaa90 100644 --- a/ftplugin/python.vim +++ b/ftplugin/python.vim @@ -1,446 +1,547 @@ -" -*- vim -*- -" FILE: python_fn.vim -" LAST MODIFICATION: 2008-08-28 8:19pm -" (C) Copyright 2001-2005 Mikael Berthe <[email protected]> -" Maintained by Jon Franklin <[email protected]> -" Version: 1.13 - -" USAGE: -" -" Save this file to $VIMFILES/ftplugin/python.vim. You can have multiple -" python ftplugins by creating $VIMFILES/ftplugin/python and saving your -" ftplugins in that directory. If saving this to the global ftplugin -" directory, this is the recommended method, since vim ships with an -" ftplugin/python.vim file already. -" You can set the global variable "g:py_select_leading_comments" to 0 -" if you don't want to select comments preceding a declaration (these -" are usually the description of the function/class). -" You can set the global variable "g:py_select_trailing_comments" to 0 -" if you don't want to select comments at the end of a function/class. -" If these variables are not defined, both leading and trailing comments -" are selected. -" Example: (in your .vimrc) "let g:py_select_leading_comments = 0" -" You may want to take a look at the 'shiftwidth' option for the -" shift commands... -" -" REQUIREMENTS: -" vim (>= 7) -" -" Shortcuts: -" ]t -- Jump to beginning of block -" ]e -- Jump to end of block -" ]v -- Select (Visual Line Mode) block -" ]< -- Shift block to left -" ]> -- Shift block to right -" ]# -- Comment selection -" ]u -- Uncomment selection -" ]c -- Select current/previous class -" ]d -- Select current/previous function -" ]<up> -- Jump to previous line with the same/lower indentation -" ]<down> -- Jump to next line with the same/lower indentation - -" Only do this when not done yet for this buffer -if exists("b:loaded_py_ftplugin") +" Vim syntax file +" Language: Python +" Maintainer: Dmitry Vasiliev <dima at hlabs dot org> +" URL: https://github.com/hdima/python-syntax +" Last Change: 2013-08-31 +" Filenames: *.py +" Version: 3.3.5 +" +" Based on python.vim (from Vim 6.1 distribution) +" by Neil Schemenauer <nas at python dot ca> +" +" Please use the following channels for reporting bugs, offering suggestions or +" feedback: + +" - python.vim issue tracker: https://github.com/hdima/python-syntax/issues +" - Email: Dmitry Vasiliev (dima at hlabs.org) +" - Send a message or follow me for updates on Twitter: `@hdima +" <https://twitter.com/hdima>`__ +" +" Contributors +" ============ +" +" List of the contributors in alphabetical order: +" +" Andrea Riciputi +" Anton Butanaev +" Caleb Adamantine +" Jeroen Ruigrok van der Werven +" John Eikenberry +" Marc Weber +" Pedro Algarvio +" pydave at GitHub +" Will Gray +" Yuri Habrusiev +" +" Options +" ======= +" +" :let OPTION_NAME = 1 Enable option +" :let OPTION_NAME = 0 Disable option +" +" +" Option to select Python version +" ------------------------------- +" +" python_version_2 Enable highlighting for Python 2 +" (Python 3 highlighting is enabled +" by default). Can also be set as +" a buffer (b:python_version_2) +" variable. +" +" You can also use the following local to buffer commands to switch +" between two highlighting modes: +" +" :Python2Syntax Switch to Python 2 highlighting +" mode +" :Python3Syntax Switch to Python 3 highlighting +" mode +" +" Option names used by the script +" ------------------------------- +" +" python_highlight_builtins Highlight builtin functions and +" objects +" python_highlight_builtin_objs Highlight builtin objects only +" python_highlight_builtin_funcs Highlight builtin functions only +" python_highlight_exceptions Highlight standard exceptions +" python_highlight_string_formatting Highlight % string formatting +" python_highlight_string_format Highlight str.format syntax +" python_highlight_string_templates Highlight string.Template syntax +" python_highlight_indent_errors Highlight indentation errors +" python_highlight_space_errors Highlight trailing spaces +" python_highlight_doctests Highlight doc-tests +" python_print_as_function Highlight 'print' statement as +" function for Python 2 +" python_highlight_file_headers_as_comments +" Highlight shebang and coding +" headers as comments +" +" python_highlight_all Enable all the options above +" NOTE: This option don't override +" any previously set options +" +" python_slow_sync Can be set to 0 for slow machines +" + +" For version 5.x: Clear all syntax items +" For versions greater than 6.x: Quit when a syntax file was already loaded +if version < 600 + syntax clear +elseif exists("b:current_syntax") finish endif -let b:loaded_py_ftplugin = 1 - -map ]t :PBoB<CR> -vmap ]t :<C-U>PBOB<CR>m'gv`` -map ]e :PEoB<CR> -vmap ]e :<C-U>PEoB<CR>m'gv`` - -map ]v ]tV]e -map ]< ]tV]e< -vmap ]< < -map ]> ]tV]e> -vmap ]> > - -map ]# :call PythonCommentSelection()<CR> -vmap ]# :call PythonCommentSelection()<CR> -map ]u :call PythonUncommentSelection()<CR> -vmap ]u :call PythonUncommentSelection()<CR> - -map ]c :call PythonSelectObject("class")<CR> -map ]d :call PythonSelectObject("function")<CR> - -map ]<up> :call PythonNextLine(-1)<CR> -map ]<down> :call PythonNextLine(1)<CR> -" You may prefer use <s-up> and <s-down>... :-) - -" jump to previous class -map ]J :call PythonDec("class", -1)<CR> -vmap ]J :call PythonDec("class", -1)<CR> - -" jump to next class -map ]j :call PythonDec("class", 1)<CR> -vmap ]j :call PythonDec("class", 1)<CR> - -" jump to previous function -map ]F :call PythonDec("function", -1)<CR> -vmap ]F :call PythonDec("function", -1)<CR> - -" jump to next function -map ]f :call PythonDec("function", 1)<CR> -vmap ]f :call PythonDec("function", 1)<CR> - - - -" Menu entries -nmenu <silent> &Python.Update\ IM-Python\ Menu - \:call UpdateMenu()<CR> -nmenu &Python.-Sep1- : -nmenu <silent> &Python.Beginning\ of\ Block<Tab>[t - \]t -nmenu <silent> &Python.End\ of\ Block<Tab>]e - \]e -nmenu &Python.-Sep2- : -nmenu <silent> &Python.Shift\ Block\ Left<Tab>]< - \]< -vmenu <silent> &Python.Shift\ Block\ Left<Tab>]< - \]< -nmenu <silent> &Python.Shift\ Block\ Right<Tab>]> - \]> -vmenu <silent> &Python.Shift\ Block\ Right<Tab>]> - \]> -nmenu &Python.-Sep3- : -vmenu <silent> &Python.Comment\ Selection<Tab>]# - \]# -nmenu <silent> &Python.Comment\ Selection<Tab>]# - \]# -vmenu <silent> &Python.Uncomment\ Selection<Tab>]u - \]u -nmenu <silent> &Python.Uncomment\ Selection<Tab>]u - \]u -nmenu &Python.-Sep4- : -nmenu <silent> &Python.Previous\ Class<Tab>]J - \]J -nmenu <silent> &Python.Next\ Class<Tab>]j - \]j -nmenu <silent> &Python.Previous\ Function<Tab>]F - \]F -nmenu <silent> &Python.Next\ Function<Tab>]f - \]f -nmenu &Python.-Sep5- : -nmenu <silent> &Python.Select\ Block<Tab>]v - \]v -nmenu <silent> &Python.Select\ Function<Tab>]d - \]d -nmenu <silent> &Python.Select\ Class<Tab>]c - \]c -nmenu &Python.-Sep6- : -nmenu <silent> &Python.Previous\ Line\ wrt\ indent<Tab>]<up> - \]<up> -nmenu <silent> &Python.Next\ Line\ wrt\ indent<Tab>]<down> - \]<down> - -:com! PBoB execute "normal ".PythonBoB(line('.'), -1, 1)."G" -:com! PEoB execute "normal ".PythonBoB(line('.'), 1, 1)."G" -:com! UpdateMenu call UpdateMenu() - - -" Go to a block boundary (-1: previous, 1: next) -" If force_sel_comments is true, 'g:py_select_trailing_comments' is ignored -function! PythonBoB(line, direction, force_sel_comments) - let ln = a:line - let ind = indent(ln) - let mark = ln - let indent_valid = strlen(getline(ln)) - let ln = ln + a:direction - if (a:direction == 1) && (!a:force_sel_comments) && - \ exists("g:py_select_trailing_comments") && - \ (!g:py_select_trailing_comments) - let sel_comments = 0 - else - let sel_comments = 1 - endif - while((ln >= 1) && (ln <= line('$'))) - if (sel_comments) || (match(getline(ln), "^\\s*#") == -1) - if (!indent_valid) - let indent_valid = strlen(getline(ln)) - let ind = indent(ln) - let mark = ln - else - if (strlen(getline(ln))) - if (indent(ln) < ind) - break - endif - let mark = ln - endif - endif - endif - let ln = ln + a:direction - endwhile +" +" Commands +" +command! -buffer Python2Syntax let b:python_version_2 = 1 | let &syntax=&syntax +command! -buffer Python3Syntax let b:python_version_2 = 0 | let &syntax=&syntax - return mark +" Enable option if it's not defined +function! s:EnableByDefault(name) + if !exists(a:name) + let {a:name} = 1 + endif endfunction +" Check if option is enabled +function! s:Enabled(name) + return exists(a:name) && {a:name} +endfunction -" Go to previous (-1) or next (1) class/function definition -function! PythonDec(obj, direction) - if (a:obj == "class") - let objregexp = "^\\s*class\\s\\+[a-zA-Z0-9_]\\+" - \ . "\\s*\\((\\([a-zA-Z0-9_,. \\t\\n]\\)*)\\)\\=\\s*:" - else - let objregexp = "^\\s*def\\s\\+[a-zA-Z0-9_]\\+\\s*(\\_[^:#]*)\\s*:" - endif - let flag = "W" - if (a:direction == -1) - let flag = flag."b" +" Is it Python 2 syntax? +function! s:Python2Syntax() + if exists("b:python_version_2") + return b:python_version_2 endif - let res = search(objregexp, flag) + return s:Enabled("g:python_version_2") endfunction +" +" Default options +" -" Comment out selected lines -" commentString is inserted in non-empty lines, and should be aligned with -" the block -function! PythonCommentSelection() range - let commentString = "#" - let cl = a:firstline - let ind = 1000 " I hope nobody use so long lines! :) +call s:EnableByDefault("g:python_slow_sync") - " Look for smallest indent - while (cl <= a:lastline) - if strlen(getline(cl)) - let cind = indent(cl) - let ind = ((ind < cind) ? ind : cind) - endif - let cl = cl + 1 - endwhile - if (ind == 1000) - let ind = 1 - else - let ind = ind + 1 +if s:Enabled("g:python_highlight_all") + call s:EnableByDefault("g:python_highlight_builtins") + if s:Enabled("g:python_highlight_builtins") + call s:EnableByDefault("g:python_highlight_builtin_objs") + call s:EnableByDefault("g:python_highlight_builtin_funcs") endif + call s:EnableByDefault("g:python_highlight_exceptions") + call s:EnableByDefault("g:python_highlight_string_formatting") + call s:EnableByDefault("g:python_highlight_string_format") + call s:EnableByDefault("g:python_highlight_string_templates") + call s:EnableByDefault("g:python_highlight_indent_errors") + call s:EnableByDefault("g:python_highlight_space_errors") + call s:EnableByDefault("g:python_highlight_doctests") + call s:EnableByDefault("g:python_print_as_function") +endif - let cl = a:firstline - execute ":".cl - " Insert commentString in each non-empty line, in column ind - while (cl <= a:lastline) - if strlen(getline(cl)) - execute "normal ".ind."|i".commentString - endif - execute "normal \<Down>" - let cl = cl + 1 - endwhile -endfunction +" +" Keywords +" -" Uncomment selected lines -function! PythonUncommentSelection() range - " commentString could be different than the one from CommentSelection() - " For example, this could be "# \\=" - let commentString = "#" - let cl = a:firstline - while (cl <= a:lastline) - let ul = substitute(getline(cl), - \"\\(\\s*\\)".commentString."\\(.*\\)$", "\\1\\2", "") - call setline(cl, ul) - let cl = cl + 1 - endwhile -endfunction +syn keyword pythonStatement break continue del +syn keyword pythonStatement exec return +syn keyword pythonStatement pass raise +syn keyword pythonStatement global assert +syn keyword pythonStatement lambda yield +syn keyword pythonStatement with +syn keyword pythonStatement def class nextgroup=pythonFunction skipwhite +syn keyword pythonRepeat for while +syn keyword pythonConditional if elif else +syn keyword pythonImport import from +syn keyword pythonException try except finally +syn keyword pythonOperator and in is not or + +if s:Python2Syntax() + if !s:Enabled("g:python_print_as_function") + syn keyword pythonStatement print + endif + syn keyword pythonImport as + syn match pythonFunction "[a-zA-Z_][a-zA-Z0-9_]*" display contained +else + syn keyword pythonStatement as nonlocal None + syn keyword pythonBoolean True False + syn match pythonFunction "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained +endif + +" +" Decorators (new in Python 2.4) +" +syn match pythonDecorator "@" display nextgroup=pythonDottedName skipwhite +syn match pythonDottedName "[a-zA-Z_][a-zA-Z0-9_]*\%(\.[a-zA-Z_][a-zA-Z0-9_]*\)*" display contained +syn match pythonDot "\." display containedin=pythonDottedName -" Select an object ("class"/"function") -function! PythonSelectObject(obj) - " Go to the object declaration - normal $ - call PythonDec(a:obj, -1) - let beg = line('.') - - if !exists("g:py_select_leading_comments") || (g:py_select_leading_comments) - let decind = indent(beg) - let cl = beg - while (cl>1) - let cl = cl - 1 - if (indent(cl) == decind) && (getline(cl)[decind] == "#") - let beg = cl - else - break - endif - endwhile +" +" Comments +" + +syn match pythonComment "#.*$" display contains=pythonTodo,@Spell +if !s:Enabled("g:python_highlight_file_headers_as_comments") + syn match pythonRun "\%^#!.*$" + syn match pythonCoding "\%^.*\%(\n.*\)\?#.*coding[:=]\s*[0-9A-Za-z-_.]\+.*$" +endif +syn keyword pythonTodo TODO FIXME XXX contained + +" +" Errors +" + +syn match pythonError "\<\d\+\D\+\>" display +syn match pythonError "[$?]" display +syn match pythonError "[&|]\{2,}" display +syn match pythonError "[=]\{3,}" display + +" Mixing spaces and tabs also may be used for pretty formatting multiline +" statements +if s:Enabled("g:python_highlight_indent_errors") + syn match pythonIndentError "^\s*\%( \t\|\t \)\s*\S"me=e-1 display +endif + +" Trailing space errors +if s:Enabled("g:python_highlight_space_errors") + syn match pythonSpaceError "\s\+$" display +endif + +" +" Strings +" + +if s:Python2Syntax() + " Python 2 strings + syn region pythonString start=+[bB]\='+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,@Spell + syn region pythonString start=+[bB]\="+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,@Spell + syn region pythonString start=+[bB]\="""+ end=+"""+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,pythonDocTest2,pythonSpaceError,@Spell + syn region pythonString start=+[bB]\='''+ end=+'''+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,pythonDocTest,pythonSpaceError,@Spell +else + " Python 3 byte strings + syn region pythonBytes start=+[bB]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonBytesError,pythonBytesContent,@Spell + syn region pythonBytes start=+[bB]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonBytesError,pythonBytesContent,@Spell + syn region pythonBytes start=+[bB]"""+ end=+"""+ keepend contains=pythonBytesError,pythonBytesContent,pythonDocTest2,pythonSpaceError,@Spell + syn region pythonBytes start=+[bB]'''+ end=+'''+ keepend contains=pythonBytesError,pythonBytesContent,pythonDocTest,pythonSpaceError,@Spell + + syn match pythonBytesError ".\+" display contained + syn match pythonBytesContent "[\u0000-\u00ff]\+" display contained contains=pythonBytesEscape,pythonBytesEscapeError +endif + +syn match pythonBytesEscape +\\[abfnrtv'"\\]+ display contained +syn match pythonBytesEscape "\\\o\o\=\o\=" display contained +syn match pythonBytesEscapeError "\\\o\{,2}[89]" display contained +syn match pythonBytesEscape "\\x\x\{2}" display contained +syn match pythonBytesEscapeError "\\x\x\=\X" display contained +syn match pythonBytesEscape "\\$" + +syn match pythonUniEscape "\\u\x\{4}" display contained +syn match pythonUniEscapeError "\\u\x\{,3}\X" display contained +syn match pythonUniEscape "\\U\x\{8}" display contained +syn match pythonUniEscapeError "\\U\x\{,7}\X" display contained +syn match pythonUniEscape "\\N{[A-Z ]\+}" display contained +syn match pythonUniEscapeError "\\N{[^A-Z ]\+}" display contained + +if s:Python2Syntax() + " Python 2 Unicode strings + syn region pythonUniString start=+[uU]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,@Spell + syn region pythonUniString start=+[uU]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,@Spell + syn region pythonUniString start=+[uU]"""+ end=+"""+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,pythonDocTest2,pythonSpaceError,@Spell + syn region pythonUniString start=+[uU]'''+ end=+'''+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,pythonDocTest,pythonSpaceError,@Spell +else + " Python 3 strings + syn region pythonString start=+'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,@Spell + syn region pythonString start=+"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,@Spell + syn region pythonString start=+"""+ end=+"""+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,pythonDocTest2,pythonSpaceError,@Spell + syn region pythonString start=+'''+ end=+'''+ keepend contains=pythonBytesEscape,pythonBytesEscapeError,pythonUniEscape,pythonUniEscapeError,pythonDocTest,pythonSpaceError,@Spell +endif + +if s:Python2Syntax() + " Python 2 Unicode raw strings + syn region pythonUniRawString start=+[uU][rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,pythonUniRawEscape,pythonUniRawEscapeError,@Spell + syn region pythonUniRawString start=+[uU][rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,pythonUniRawEscape,pythonUniRawEscapeError,@Spell + syn region pythonUniRawString start=+[uU][rR]"""+ end=+"""+ keepend contains=pythonUniRawEscape,pythonUniRawEscapeError,pythonDocTest2,pythonSpaceError,@Spell + syn region pythonUniRawString start=+[uU][rR]'''+ end=+'''+ keepend contains=pythonUniRawEscape,pythonUniRawEscapeError,pythonDocTest,pythonSpaceError,@Spell + + syn match pythonUniRawEscape "\([^\\]\(\\\\\)*\)\@<=\\u\x\{4}" display contained + syn match pythonUniRawEscapeError "\([^\\]\(\\\\\)*\)\@<=\\u\x\{,3}\X" display contained +endif + +" Python 2/3 raw strings +if s:Python2Syntax() + syn region pythonRawString start=+[bB]\=[rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,@Spell + syn region pythonRawString start=+[bB]\=[rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,@Spell + syn region pythonRawString start=+[bB]\=[rR]"""+ end=+"""+ keepend contains=pythonDocTest2,pythonSpaceError,@Spell + syn region pythonRawString start=+[bB]\=[rR]'''+ end=+'''+ keepend contains=pythonDocTest,pythonSpaceError,@Spell +else + syn region pythonRawString start=+[rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,@Spell + syn region pythonRawString start=+[rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,@Spell + syn region pythonRawString start=+[rR]"""+ end=+"""+ keepend contains=pythonDocTest2,pythonSpaceError,@Spell + syn region pythonRawString start=+[rR]'''+ end=+'''+ keepend contains=pythonDocTest,pythonSpaceError,@Spell + + syn region pythonRawBytes start=+[bB][rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,@Spell + syn region pythonRawBytes start=+[bB][rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,@Spell + syn region pythonRawBytes start=+[bB][rR]"""+ end=+"""+ keepend contains=pythonDocTest2,pythonSpaceError,@Spell + syn region pythonRawBytes start=+[bB][rR]'''+ end=+'''+ keepend contains=pythonDocTest,pythonSpaceError,@Spell +endif + +syn match pythonRawEscape +\\['"]+ display transparent contained + +if s:Enabled("g:python_highlight_string_formatting") + " % operator string formatting + if s:Python2Syntax() + syn match pythonStrFormatting "%\%(([^)]\+)\)\=[-#0 +]*\d*\%(\.\d\+\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString + syn match pythonStrFormatting "%[-#0 +]*\%(\*\|\d\+\)\=\%(\.\%(\*\|\d\+\)\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString + else + syn match pythonStrFormatting "%\%(([^)]\+)\)\=[-#0 +]*\d*\%(\.\d\+\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonRawString + syn match pythonStrFormatting "%[-#0 +]*\%(\*\|\d\+\)\=\%(\.\%(\*\|\d\+\)\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonRawString endif +endif - if (a:obj == "class") - let eod = "\\(^\\s*class\\s\\+[a-zA-Z0-9_]\\+\\s*" - \ . "\\((\\([a-zA-Z0-9_,. \\t\\n]\\)*)\\)\\=\\s*\\)\\@<=:" +if s:Enabled("g:python_highlight_string_format") + " str.format syntax + if s:Python2Syntax() + syn match pythonStrFormat "{{\|}}" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString + syn match pythonStrFormat "{\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)\=\%(\.\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\[\%(\d\+\|[^!:\}]\+\)\]\)*\%(![rsa]\)\=\%(:\%({\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)}\|\%([^}]\=[<>=^]\)\=[ +-]\=#\=0\=\d*,\=\%(\.\d\+\)\=[bcdeEfFgGnosxX%]\=\)\=\)\=}" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString else - let eod = "\\(^\\s*def\\s\\+[a-zA-Z0-9_]\\+\\s*(\\_[^:#]*)\\s*\\)\\@<=:" + syn match pythonStrFormat "{{\|}}" contained containedin=pythonString,pythonRawString + syn match pythonStrFormat "{\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)\=\%(\.\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\[\%(\d\+\|[^!:\}]\+\)\]\)*\%(![rsa]\)\=\%(:\%({\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)}\|\%([^}]\=[<>=^]\)\=[ +-]\=#\=0\=\d*,\=\%(\.\d\+\)\=[bcdeEfFgGnosxX%]\=\)\=\)\=}" contained containedin=pythonString,pythonRawString endif - " Look for the end of the declaration (not always the same line!) - call search(eod, "") - - " Is it a one-line definition? - if match(getline('.'), "^\\s*\\(#.*\\)\\=$", col('.')) == -1 - let cl = line('.') - execute ":".beg - execute "normal V".cl."G" +endif + +if s:Enabled("g:python_highlight_string_templates") + " string.Template format + if s:Python2Syntax() + syn match pythonStrTemplate "\$\$" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString + syn match pythonStrTemplate "\${[a-zA-Z_][a-zA-Z0-9_]*}" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString + syn match pythonStrTemplate "\$[a-zA-Z_][a-zA-Z0-9_]*" contained containedin=pythonString,pythonUniString,pythonUniRawString,pythonRawString else - " Select the whole block - execute "normal \<Down>" - let cl = line('.') - execute ":".beg - execute "normal V".PythonBoB(cl, 1, 0)."G" + syn match pythonStrTemplate "\$\$" contained containedin=pythonString,pythonRawString + syn match pythonStrTemplate "\${[a-zA-Z_][a-zA-Z0-9_]*}" contained containedin=pythonString,pythonRawString + syn match pythonStrTemplate "\$[a-zA-Z_][a-zA-Z0-9_]*" contained containedin=pythonString,pythonRawString endif -endfunction +endif +if s:Enabled("g:python_highlight_doctests") + " DocTests + syn region pythonDocTest start="^\s*>>>" end=+'''+he=s-1 end="^\s*$" contained + syn region pythonDocTest2 start="^\s*>>>" end=+"""+he=s-1 end="^\s*$" contained +endif -" Jump to the next line with the same (or lower) indentation -" Useful for moving between "if" and "else", for example. -function! PythonNextLine(direction) - let ln = line('.') - let ind = indent(ln) - let indent_valid = strlen(getline(ln)) - let ln = ln + a:direction - - while((ln >= 1) && (ln <= line('$'))) - if (!indent_valid) && strlen(getline(ln)) - break - else - if (strlen(getline(ln))) - if (indent(ln) <= ind) - break - endif - endif - endif - let ln = ln + a:direction - endwhile +" +" Numbers (ints, longs, floats, complex) +" - execute "normal ".ln."G" -endfunction +if s:Python2Syntax() + syn match pythonHexError "\<0[xX]\x*[g-zG-Z]\+\x*[lL]\=\>" display + syn match pythonOctError "\<0[oO]\=\o*\D\+\d*[lL]\=\>" display + syn match pythonBinError "\<0[bB][01]*\D\+\d*[lL]\=\>" display + + syn match pythonHexNumber "\<0[xX]\x\+[lL]\=\>" display + syn match pythonOctNumber "\<0[oO]\o\+[lL]\=\>" display + syn match pythonBinNumber "\<0[bB][01]\+[lL]\=\>" display + + syn match pythonNumberError "\<\d\+\D[lL]\=\>" display + syn match pythonNumber "\<\d[lL]\=\>" display + syn match pythonNumber "\<[0-9]\d\+[lL]\=\>" display + syn match pythonNumber "\<\d\+[lLjJ]\>" display + + syn match pythonOctError "\<0[oO]\=\o*[8-9]\d*[lL]\=\>" display + syn match pythonBinError "\<0[bB][01]*[2-9]\d*[lL]\=\>" display +else + syn match pythonHexError "\<0[xX]\x*[g-zG-Z]\x*\>" display + syn match pythonOctError "\<0[oO]\=\o*\D\+\d*\>" display + syn match pythonBinError "\<0[bB][01]*\D\+\d*\>" display + + syn match pythonHexNumber "\<0[xX]\x\+\>" display + syn match pythonOctNumber "\<0[oO]\o\+\>" display + syn match pythonBinNumber "\<0[bB][01]\+\>" display + + syn match pythonNumberError "\<\d\+\D\>" display + syn match pythonNumberError "\<0\d\+\>" display + syn match pythonNumber "\<\d\>" display + syn match pythonNumber "\<[1-9]\d\+\>" display + syn match pythonNumber "\<\d\+[jJ]\>" display + + syn match pythonOctError "\<0[oO]\=\o*[8-9]\d*\>" display + syn match pythonBinError "\<0[bB][01]*[2-9]\d*\>" display +endif + +syn match pythonFloat "\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>" display +syn match pythonFloat "\<\d\+[eE][+-]\=\d\+[jJ]\=\>" display +syn match pythonFloat "\<\d\+\.\d*\%([eE][+-]\=\d\+\)\=[jJ]\=" display + +" +" Builtin objects and types +" -function! UpdateMenu() - " delete menu if it already exists, then rebuild it. - " this is necessary in case you've got multiple buffers open - " a future enhancement to this would be to make the menu aware of - " all buffers currently open, and group classes and functions by buffer - if exists("g:menuran") - aunmenu IM-Python +if s:Enabled("g:python_highlight_builtin_objs") + if s:Python2Syntax() + syn keyword pythonBuiltinObj None + syn keyword pythonBoolean True False endif - let restore_fe = &foldenable - set nofoldenable - " preserve disposition of window and cursor - let cline=line('.') - let ccol=col('.') - 1 - norm H - let hline=line('.') - " create the menu - call MenuBuilder() - " restore disposition of window and cursor - exe "norm ".hline."Gzt" - let dnscroll=cline-hline - exe "norm ".dnscroll."j".ccol."l" - let &foldenable = restore_fe -endfunction + syn keyword pythonBuiltinObj Ellipsis NotImplemented + syn keyword pythonBuiltinObj __debug__ __doc__ __file__ __name__ __package__ +endif -function! MenuBuilder() - norm gg0 - let currentclass = -1 - let classlist = [] - let parentclass = "" - while line(".") < line("$") - " search for a class or function - if match ( getline("."), '^\s*class\s\+[_a-zA-Z].*\|^\s*def\s\+[_a-zA-Z].*' ) != -1 - norm ^ - let linenum = line('.') - let indentcol = col('.') - norm "nye - let classordef=@n - norm w"nywge - let objname=@n - let parentclass = FindParentClass(classlist, indentcol) - if classordef == "class" - call AddClass(objname, linenum, parentclass) - else " this is a function - call AddFunction(objname, linenum, parentclass) - endif - " We actually created a menu, so lets set the global variable - let g:menuran=1 - call RebuildClassList(classlist, [objname, indentcol], classordef) - endif " line matched - norm j - endwhile -endfunction +" +" Builtin functions +" -" classlist contains the list of nested classes we are in. -" in most cases it will be empty or contain a single class -" but where a class is nested within another, it will contain 2 or more -" this function adds or removes classes from the list based on indentation -function! RebuildClassList(classlist, newclass, classordef) - let i = len(a:classlist) - 1 - while i > -1 - if a:newclass[1] <= a:classlist[i][1] - call remove(a:classlist, i) +if s:Enabled("g:python_highlight_builtin_funcs") + if s:Python2Syntax() + syn keyword pythonBuiltinFunc apply basestring buffer callable coerce + syn keyword pythonBuiltinFunc execfile file help intern long raw_input + syn keyword pythonBuiltinFunc reduce reload unichr unicode xrange + if s:Enabled("g:python_print_as_function") + syn keyword pythonBuiltinFunc print endif - let i = i - 1 - endwhile - if a:classordef == "class" - call add(a:classlist, a:newclass) + else + syn keyword pythonBuiltinFunc ascii exec memoryview print endif -endfunction + syn keyword pythonBuiltinFunc __import__ abs all any + syn keyword pythonBuiltinFunc bin bool bytearray bytes + syn keyword pythonBuiltinFunc chr classmethod cmp compile complex + syn keyword pythonBuiltinFunc delattr dict dir divmod enumerate eval + syn keyword pythonBuiltinFunc filter float format frozenset getattr + syn keyword pythonBuiltinFunc globals hasattr hash hex id + syn keyword pythonBuiltinFunc input int isinstance + syn keyword pythonBuiltinFunc issubclass iter len list locals map max + syn keyword pythonBuiltinFunc min next object oct open ord + syn keyword pythonBuiltinFunc pow property range + syn keyword pythonBuiltinFunc repr reversed round set setattr + syn keyword pythonBuiltinFunc slice sorted staticmethod str sum super tuple + syn keyword pythonBuiltinFunc type vars zip +endif -" we found a class or function, determine its parent class based on -" indentation and what's contained in classlist -function! FindParentClass(classlist, indentcol) - let i = 0 - let parentclass = "" - while i < len(a:classlist) - if a:indentcol <= a:classlist[i][1] - break - else - if len(parentclass) == 0 - let parentclass = a:classlist[i][0] - else - let parentclass = parentclass.'\.'.a:classlist[i][0] - endif - endif - let i = i + 1 - endwhile - return parentclass -endfunction +" +" Builtin exceptions and warnings +" -" add a class to the menu -function! AddClass(classname, lineno, parentclass) - if len(a:parentclass) > 0 - let classstring = a:parentclass.'\.'.a:classname +if s:Enabled("g:python_highlight_exceptions") + if s:Python2Syntax() + syn keyword pythonExClass StandardError else - let classstring = a:classname + syn keyword pythonExClass BlockingIOError ChildProcessError + syn keyword pythonExClass ConnectionError BrokenPipeError + syn keyword pythonExClass ConnectionAbortedError ConnectionRefusedError + syn keyword pythonExClass ConnectionResetError FileExistsError + syn keyword pythonExClass FileNotFoundError InterruptedError + syn keyword pythonExClass IsADirectoryError NotADirectoryError + syn keyword pythonExClass PermissionError ProcessLookupError TimeoutError + + syn keyword pythonExClass ResourceWarning endif - exe 'menu IM-Python.classes.'.classstring.' :call <SID>JumpToAndUnfold('.a:lineno.')<CR>' -endfunction + syn keyword pythonExClass BaseException + syn keyword pythonExClass Exception ArithmeticError + syn keyword pythonExClass LookupError EnvironmentError + + syn keyword pythonExClass AssertionError AttributeError BufferError EOFError + syn keyword pythonExClass FloatingPointError GeneratorExit IOError + syn keyword pythonExClass ImportError IndexError KeyError + syn keyword pythonExClass KeyboardInterrupt MemoryError NameError + syn keyword pythonExClass NotImplementedError OSError OverflowError + syn keyword pythonExClass ReferenceError RuntimeError StopIteration + syn keyword pythonExClass SyntaxError IndentationError TabError + syn keyword pythonExClass SystemError SystemExit TypeError + syn keyword pythonExClass UnboundLocalError UnicodeError + syn keyword pythonExClass UnicodeEncodeError UnicodeDecodeError + syn keyword pythonExClass UnicodeTranslateError ValueError VMSError + syn keyword pythonExClass WindowsError ZeroDivisionError + + syn keyword pythonExClass Warning UserWarning BytesWarning DeprecationWarning + syn keyword pythonExClass PendingDepricationWarning SyntaxWarning + syn keyword pythonExClass RuntimeWarning FutureWarning + syn keyword pythonExClass ImportWarning UnicodeWarning +endif -" add a function to the menu, grouped by member class -function! AddFunction(functionname, lineno, parentclass) - if len(a:parentclass) > 0 - let funcstring = a:parentclass.'.'.a:functionname +if s:Enabled("g:python_slow_sync") + syn sync minlines=2000 +else + " This is fast but code inside triple quoted strings screws it up. It + " is impossible to fix because the only way to know if you are inside a + " triple quoted string is to start from the beginning of the file. + syn sync match pythonSync grouphere NONE "):$" + syn sync maxlines=200 +endif + +if version >= 508 || !exists("did_python_syn_inits") + if version <= 508 + let did_python_syn_inits = 1 + command -nargs=+ HiLink hi link <args> else - let funcstring = a:functionname + command -nargs=+ HiLink hi def link <args> endif - exe 'menu IM-Python.functions.'.funcstring.' :call <SID>JumpToAndUnfold('.a:lineno.')<CR>' -endfunction + HiLink pythonStatement Statement + HiLink pythonImport Include + HiLink pythonFunction Function + HiLink pythonConditional Conditional + HiLink pythonRepeat Repeat + HiLink pythonException Exception + HiLink pythonOperator Operator + + HiLink pythonDecorator Define + HiLink pythonDottedName Function + HiLink pythonDot Normal + + HiLink pythonComment Comment + if !s:Enabled("g:python_highlight_file_headers_as_comments") + HiLink pythonCoding Special + HiLink pythonRun Special + endif + HiLink pythonTodo Todo + + HiLink pythonError Error + HiLink pythonIndentError Error + HiLink pythonSpaceError Error + + HiLink pythonString String + HiLink pythonRawString String + + HiLink pythonUniEscape Special + HiLink pythonUniEscapeError Error -function! s:JumpToAndUnfold(line) - " Go to the right line - execute 'normal '.a:line.'gg' - " Check to see if we are in a fold - let lvl = foldlevel(a:line) - if lvl != 0 - " and if so, then expand the fold out, other wise, ignore this part. - execute 'normal 15zo' + if s:Python2Syntax() + HiLink pythonUniString String + HiLink pythonUniRawString String + HiLink pythonUniRawEscape Special + HiLink pythonUniRawEscapeError Error + else + HiLink pythonBytes String + HiLink pythonRawBytes String + HiLink pythonBytesContent String + HiLink pythonBytesError Error + HiLink pythonBytesEscape Special + HiLink pythonBytesEscapeError Error endif -endfunction -"" This one will work only on vim 6.2 because of the try/catch expressions. -" function! s:JumpToAndUnfoldWithExceptions(line) -" try -" execute 'normal '.a:line.'gg15zo' -" catch /^Vim\((\a\+)\)\=:E490:/ -" " Do nothing, just consume the error -" endtry -"endfunction + HiLink pythonStrFormatting Special + HiLink pythonStrFormat Special + HiLink pythonStrTemplate Special + + HiLink pythonDocTest Special + HiLink pythonDocTest2 Special + + HiLink pythonNumber Number + HiLink pythonHexNumber Number + HiLink pythonOctNumber Number + HiLink pythonBinNumber Number + HiLink pythonFloat Float + HiLink pythonNumberError Error + HiLink pythonOctError Error + HiLink pythonHexError Error + HiLink pythonBinError Error + HiLink pythonBoolean Boolean -" vim:set et sts=2 sw=2: + HiLink pythonBuiltinObj Structure + HiLink pythonBuiltinFunc Function + + HiLink pythonExClass Structure + + delcommand HiLink +endif +let b:current_syntax = "python"
sophacles/vim-bundle-python
caaf7564696e6319a465aafd960bd69d7b5bddd6
fixed settings to be buffer-local instead of global, as that makes way more sense
diff --git a/after/ftplugin/python/python.vim b/after/ftplugin/python/python.vim index 29ffdf5..fcf3d9f 100644 --- a/after/ftplugin/python/python.vim +++ b/after/ftplugin/python/python.vim @@ -1,6 +1,5 @@ -set fdm=indent +setlocal fdm=indent let python_highlight_all=1 -set sr -set expandtab -set sw=4 +setlocal expandtab +setlocal sw=4
sophacles/vim-bundle-python
3ce3325dcbda9f58a8fd34a94bc7e6d8d3865680
standardized my vimbundle readme format
diff --git a/README b/README index a06e982..13cfb28 100644 --- a/README +++ b/README @@ -1,11 +1,12 @@ Personal stuff: * after/ftplugin/python/* just setting some vars and whatnot. ipy.vim is from back in the day when i - was all about ipython<->vim communication. + was all about ipython<->vim communication. External file sources: -* syntax/python.vim (vimscript #790) - http://www.vim.org/scripts/download_script.php?src_id=12804 - -* ftplugin/python.vim (vimscript #30) - http://www.vim.org/scripts/download_script.php?src_id=9196 +* syntax/python.vim (vimscript #790) by Dmitri Vasiliev + http://www.vim.org/scripts/script.php?script_id=790 + current version: 2.6.6 +* ftplugin/python.vim (vimscript #30) by Jon Franklin + http://www.vim.org/scripts/script.php?script_id=30 + current version: 1.13
sophacles/vim-bundle-python
27efaa712aaf0d0c40c0cc30b133c365629cc952
Added some personal vim stuff
diff --git a/README b/README index 672511d..a06e982 100644 --- a/README +++ b/README @@ -1,5 +1,11 @@ Personal stuff: +* after/ftplugin/python/* + just setting some vars and whatnot. ipy.vim is from back in the day when i + was all about ipython<->vim communication. External file sources: -* syntax/python.vim +* syntax/python.vim (vimscript #790) http://www.vim.org/scripts/download_script.php?src_id=12804 + +* ftplugin/python.vim (vimscript #30) + http://www.vim.org/scripts/download_script.php?src_id=9196 diff --git a/after/ftplugin/python/ipy.vim b/after/ftplugin/python/ipy.vim new file mode 100644 index 0000000..cb05cf5 --- /dev/null +++ b/after/ftplugin/python/ipy.vim @@ -0,0 +1,67 @@ +if !exists("$IPY_SESSION") + finish +endif + +" set up the python interpreter within vim, to have all the right modules +" imported, as well as certain useful globals set +python import socket +python import os +python import vim +python IPYSERVER = None + +python << EOF +# do we have a connection to the ipython instance? +def check_server(): + global IPYSERVER + if IPYSERVER: + return True + else: + return False + +# connect to the ipython server, if we need to +def connect(): + global IPYSERVER + if check_server(): + return + try: + IPYSERVER = socket.socket(socket.AF_UNIX) + IPYSERVER.connect(os.environ.get('IPY_SERVER')) + except: + IPYSERVER = None + +def disconnect(): + if IPYSERVER: + IPYSERVER.close() + +def send(cmd): + x = 0 + while True: + x += IPYSERVER.send(cmd) + if x < len(cmd): + cmd = cmd[x:] + else: + break + +def run_this_file(): + if check_server(): + send('run %s' % (vim.current.buffer.name,)) + else: + raise Exception, "Not connected to an IPython server" +EOF + +fun! <SID>toggle_send_on_save() + if exists("s:ssos") && s:ssos == 1 + let s:ssos = 0 + au! BufWritePost *.py :py run_this_file() + echo "Autosend Off" + else + let s:ssos = 1 + au BufWritePost *.py :py run_this_file() + echo "Autowsend On" + endif +endfun + +map <silent> <F5> :python run_this_file()<CR> +imap <silent> <C-F5> <ESC><F5>a +map <F7> :call <SID>toggle_send_on_save()<CR> +py connect() diff --git a/after/ftplugin/python/python.vim b/after/ftplugin/python/python.vim new file mode 100644 index 0000000..29ffdf5 --- /dev/null +++ b/after/ftplugin/python/python.vim @@ -0,0 +1,6 @@ +set fdm=indent +let python_highlight_all=1 +set sr +set expandtab +set sw=4 +
sophacles/vim-bundle-python
a36d968cc05be80d94036cadfc6bfa8820d87d8b
added some ftplugin goodness
diff --git a/ftplugin/python.vim b/ftplugin/python.vim new file mode 100644 index 0000000..7c7cf21 --- /dev/null +++ b/ftplugin/python.vim @@ -0,0 +1,446 @@ +" -*- vim -*- +" FILE: python_fn.vim +" LAST MODIFICATION: 2008-08-28 8:19pm +" (C) Copyright 2001-2005 Mikael Berthe <[email protected]> +" Maintained by Jon Franklin <[email protected]> +" Version: 1.13 + +" USAGE: +" +" Save this file to $VIMFILES/ftplugin/python.vim. You can have multiple +" python ftplugins by creating $VIMFILES/ftplugin/python and saving your +" ftplugins in that directory. If saving this to the global ftplugin +" directory, this is the recommended method, since vim ships with an +" ftplugin/python.vim file already. +" You can set the global variable "g:py_select_leading_comments" to 0 +" if you don't want to select comments preceding a declaration (these +" are usually the description of the function/class). +" You can set the global variable "g:py_select_trailing_comments" to 0 +" if you don't want to select comments at the end of a function/class. +" If these variables are not defined, both leading and trailing comments +" are selected. +" Example: (in your .vimrc) "let g:py_select_leading_comments = 0" +" You may want to take a look at the 'shiftwidth' option for the +" shift commands... +" +" REQUIREMENTS: +" vim (>= 7) +" +" Shortcuts: +" ]t -- Jump to beginning of block +" ]e -- Jump to end of block +" ]v -- Select (Visual Line Mode) block +" ]< -- Shift block to left +" ]> -- Shift block to right +" ]# -- Comment selection +" ]u -- Uncomment selection +" ]c -- Select current/previous class +" ]d -- Select current/previous function +" ]<up> -- Jump to previous line with the same/lower indentation +" ]<down> -- Jump to next line with the same/lower indentation + +" Only do this when not done yet for this buffer +if exists("b:loaded_py_ftplugin") + finish +endif +let b:loaded_py_ftplugin = 1 + +map ]t :PBoB<CR> +vmap ]t :<C-U>PBOB<CR>m'gv`` +map ]e :PEoB<CR> +vmap ]e :<C-U>PEoB<CR>m'gv`` + +map ]v ]tV]e +map ]< ]tV]e< +vmap ]< < +map ]> ]tV]e> +vmap ]> > + +map ]# :call PythonCommentSelection()<CR> +vmap ]# :call PythonCommentSelection()<CR> +map ]u :call PythonUncommentSelection()<CR> +vmap ]u :call PythonUncommentSelection()<CR> + +map ]c :call PythonSelectObject("class")<CR> +map ]d :call PythonSelectObject("function")<CR> + +map ]<up> :call PythonNextLine(-1)<CR> +map ]<down> :call PythonNextLine(1)<CR> +" You may prefer use <s-up> and <s-down>... :-) + +" jump to previous class +map ]J :call PythonDec("class", -1)<CR> +vmap ]J :call PythonDec("class", -1)<CR> + +" jump to next class +map ]j :call PythonDec("class", 1)<CR> +vmap ]j :call PythonDec("class", 1)<CR> + +" jump to previous function +map ]F :call PythonDec("function", -1)<CR> +vmap ]F :call PythonDec("function", -1)<CR> + +" jump to next function +map ]f :call PythonDec("function", 1)<CR> +vmap ]f :call PythonDec("function", 1)<CR> + + + +" Menu entries +nmenu <silent> &Python.Update\ IM-Python\ Menu + \:call UpdateMenu()<CR> +nmenu &Python.-Sep1- : +nmenu <silent> &Python.Beginning\ of\ Block<Tab>[t + \]t +nmenu <silent> &Python.End\ of\ Block<Tab>]e + \]e +nmenu &Python.-Sep2- : +nmenu <silent> &Python.Shift\ Block\ Left<Tab>]< + \]< +vmenu <silent> &Python.Shift\ Block\ Left<Tab>]< + \]< +nmenu <silent> &Python.Shift\ Block\ Right<Tab>]> + \]> +vmenu <silent> &Python.Shift\ Block\ Right<Tab>]> + \]> +nmenu &Python.-Sep3- : +vmenu <silent> &Python.Comment\ Selection<Tab>]# + \]# +nmenu <silent> &Python.Comment\ Selection<Tab>]# + \]# +vmenu <silent> &Python.Uncomment\ Selection<Tab>]u + \]u +nmenu <silent> &Python.Uncomment\ Selection<Tab>]u + \]u +nmenu &Python.-Sep4- : +nmenu <silent> &Python.Previous\ Class<Tab>]J + \]J +nmenu <silent> &Python.Next\ Class<Tab>]j + \]j +nmenu <silent> &Python.Previous\ Function<Tab>]F + \]F +nmenu <silent> &Python.Next\ Function<Tab>]f + \]f +nmenu &Python.-Sep5- : +nmenu <silent> &Python.Select\ Block<Tab>]v + \]v +nmenu <silent> &Python.Select\ Function<Tab>]d + \]d +nmenu <silent> &Python.Select\ Class<Tab>]c + \]c +nmenu &Python.-Sep6- : +nmenu <silent> &Python.Previous\ Line\ wrt\ indent<Tab>]<up> + \]<up> +nmenu <silent> &Python.Next\ Line\ wrt\ indent<Tab>]<down> + \]<down> + +:com! PBoB execute "normal ".PythonBoB(line('.'), -1, 1)."G" +:com! PEoB execute "normal ".PythonBoB(line('.'), 1, 1)."G" +:com! UpdateMenu call UpdateMenu() + + +" Go to a block boundary (-1: previous, 1: next) +" If force_sel_comments is true, 'g:py_select_trailing_comments' is ignored +function! PythonBoB(line, direction, force_sel_comments) + let ln = a:line + let ind = indent(ln) + let mark = ln + let indent_valid = strlen(getline(ln)) + let ln = ln + a:direction + if (a:direction == 1) && (!a:force_sel_comments) && + \ exists("g:py_select_trailing_comments") && + \ (!g:py_select_trailing_comments) + let sel_comments = 0 + else + let sel_comments = 1 + endif + + while((ln >= 1) && (ln <= line('$'))) + if (sel_comments) || (match(getline(ln), "^\\s*#") == -1) + if (!indent_valid) + let indent_valid = strlen(getline(ln)) + let ind = indent(ln) + let mark = ln + else + if (strlen(getline(ln))) + if (indent(ln) < ind) + break + endif + let mark = ln + endif + endif + endif + let ln = ln + a:direction + endwhile + + return mark +endfunction + + +" Go to previous (-1) or next (1) class/function definition +function! PythonDec(obj, direction) + if (a:obj == "class") + let objregexp = "^\\s*class\\s\\+[a-zA-Z0-9_]\\+" + \ . "\\s*\\((\\([a-zA-Z0-9_,. \\t\\n]\\)*)\\)\\=\\s*:" + else + let objregexp = "^\\s*def\\s\\+[a-zA-Z0-9_]\\+\\s*(\\_[^:#]*)\\s*:" + endif + let flag = "W" + if (a:direction == -1) + let flag = flag."b" + endif + let res = search(objregexp, flag) +endfunction + + +" Comment out selected lines +" commentString is inserted in non-empty lines, and should be aligned with +" the block +function! PythonCommentSelection() range + let commentString = "#" + let cl = a:firstline + let ind = 1000 " I hope nobody use so long lines! :) + + " Look for smallest indent + while (cl <= a:lastline) + if strlen(getline(cl)) + let cind = indent(cl) + let ind = ((ind < cind) ? ind : cind) + endif + let cl = cl + 1 + endwhile + if (ind == 1000) + let ind = 1 + else + let ind = ind + 1 + endif + + let cl = a:firstline + execute ":".cl + " Insert commentString in each non-empty line, in column ind + while (cl <= a:lastline) + if strlen(getline(cl)) + execute "normal ".ind."|i".commentString + endif + execute "normal \<Down>" + let cl = cl + 1 + endwhile +endfunction + +" Uncomment selected lines +function! PythonUncommentSelection() range + " commentString could be different than the one from CommentSelection() + " For example, this could be "# \\=" + let commentString = "#" + let cl = a:firstline + while (cl <= a:lastline) + let ul = substitute(getline(cl), + \"\\(\\s*\\)".commentString."\\(.*\\)$", "\\1\\2", "") + call setline(cl, ul) + let cl = cl + 1 + endwhile +endfunction + + +" Select an object ("class"/"function") +function! PythonSelectObject(obj) + " Go to the object declaration + normal $ + call PythonDec(a:obj, -1) + let beg = line('.') + + if !exists("g:py_select_leading_comments") || (g:py_select_leading_comments) + let decind = indent(beg) + let cl = beg + while (cl>1) + let cl = cl - 1 + if (indent(cl) == decind) && (getline(cl)[decind] == "#") + let beg = cl + else + break + endif + endwhile + endif + + if (a:obj == "class") + let eod = "\\(^\\s*class\\s\\+[a-zA-Z0-9_]\\+\\s*" + \ . "\\((\\([a-zA-Z0-9_,. \\t\\n]\\)*)\\)\\=\\s*\\)\\@<=:" + else + let eod = "\\(^\\s*def\\s\\+[a-zA-Z0-9_]\\+\\s*(\\_[^:#]*)\\s*\\)\\@<=:" + endif + " Look for the end of the declaration (not always the same line!) + call search(eod, "") + + " Is it a one-line definition? + if match(getline('.'), "^\\s*\\(#.*\\)\\=$", col('.')) == -1 + let cl = line('.') + execute ":".beg + execute "normal V".cl."G" + else + " Select the whole block + execute "normal \<Down>" + let cl = line('.') + execute ":".beg + execute "normal V".PythonBoB(cl, 1, 0)."G" + endif +endfunction + + +" Jump to the next line with the same (or lower) indentation +" Useful for moving between "if" and "else", for example. +function! PythonNextLine(direction) + let ln = line('.') + let ind = indent(ln) + let indent_valid = strlen(getline(ln)) + let ln = ln + a:direction + + while((ln >= 1) && (ln <= line('$'))) + if (!indent_valid) && strlen(getline(ln)) + break + else + if (strlen(getline(ln))) + if (indent(ln) <= ind) + break + endif + endif + endif + let ln = ln + a:direction + endwhile + + execute "normal ".ln."G" +endfunction + +function! UpdateMenu() + " delete menu if it already exists, then rebuild it. + " this is necessary in case you've got multiple buffers open + " a future enhancement to this would be to make the menu aware of + " all buffers currently open, and group classes and functions by buffer + if exists("g:menuran") + aunmenu IM-Python + endif + let restore_fe = &foldenable + set nofoldenable + " preserve disposition of window and cursor + let cline=line('.') + let ccol=col('.') - 1 + norm H + let hline=line('.') + " create the menu + call MenuBuilder() + " restore disposition of window and cursor + exe "norm ".hline."Gzt" + let dnscroll=cline-hline + exe "norm ".dnscroll."j".ccol."l" + let &foldenable = restore_fe +endfunction + +function! MenuBuilder() + norm gg0 + let currentclass = -1 + let classlist = [] + let parentclass = "" + while line(".") < line("$") + " search for a class or function + if match ( getline("."), '^\s*class\s\+[_a-zA-Z].*\|^\s*def\s\+[_a-zA-Z].*' ) != -1 + norm ^ + let linenum = line('.') + let indentcol = col('.') + norm "nye + let classordef=@n + norm w"nywge + let objname=@n + let parentclass = FindParentClass(classlist, indentcol) + if classordef == "class" + call AddClass(objname, linenum, parentclass) + else " this is a function + call AddFunction(objname, linenum, parentclass) + endif + " We actually created a menu, so lets set the global variable + let g:menuran=1 + call RebuildClassList(classlist, [objname, indentcol], classordef) + endif " line matched + norm j + endwhile +endfunction + +" classlist contains the list of nested classes we are in. +" in most cases it will be empty or contain a single class +" but where a class is nested within another, it will contain 2 or more +" this function adds or removes classes from the list based on indentation +function! RebuildClassList(classlist, newclass, classordef) + let i = len(a:classlist) - 1 + while i > -1 + if a:newclass[1] <= a:classlist[i][1] + call remove(a:classlist, i) + endif + let i = i - 1 + endwhile + if a:classordef == "class" + call add(a:classlist, a:newclass) + endif +endfunction + +" we found a class or function, determine its parent class based on +" indentation and what's contained in classlist +function! FindParentClass(classlist, indentcol) + let i = 0 + let parentclass = "" + while i < len(a:classlist) + if a:indentcol <= a:classlist[i][1] + break + else + if len(parentclass) == 0 + let parentclass = a:classlist[i][0] + else + let parentclass = parentclass.'\.'.a:classlist[i][0] + endif + endif + let i = i + 1 + endwhile + return parentclass +endfunction + +" add a class to the menu +function! AddClass(classname, lineno, parentclass) + if len(a:parentclass) > 0 + let classstring = a:parentclass.'\.'.a:classname + else + let classstring = a:classname + endif + exe 'menu IM-Python.classes.'.classstring.' :call <SID>JumpToAndUnfold('.a:lineno.')<CR>' +endfunction + +" add a function to the menu, grouped by member class +function! AddFunction(functionname, lineno, parentclass) + if len(a:parentclass) > 0 + let funcstring = a:parentclass.'.'.a:functionname + else + let funcstring = a:functionname + endif + exe 'menu IM-Python.functions.'.funcstring.' :call <SID>JumpToAndUnfold('.a:lineno.')<CR>' +endfunction + + +function! s:JumpToAndUnfold(line) + " Go to the right line + execute 'normal '.a:line.'gg' + " Check to see if we are in a fold + let lvl = foldlevel(a:line) + if lvl != 0 + " and if so, then expand the fold out, other wise, ignore this part. + execute 'normal 15zo' + endif +endfunction + +"" This one will work only on vim 6.2 because of the try/catch expressions. +" function! s:JumpToAndUnfoldWithExceptions(line) +" try +" execute 'normal '.a:line.'gg15zo' +" catch /^Vim\((\a\+)\)\=:E490:/ +" " Do nothing, just consume the error +" endtry +"endfunction + + +" vim:set et sts=2 sw=2: +
sophacles/vim-bundle-python
73ecea5788b1f6274d8a348bb833bc750646c4df
Added syntax highlighting.
diff --git a/README b/README index e69de29..672511d 100644 --- a/README +++ b/README @@ -0,0 +1,5 @@ +Personal stuff: + +External file sources: +* syntax/python.vim + http://www.vim.org/scripts/download_script.php?src_id=12804 diff --git a/syntax/python.vim b/syntax/python.vim new file mode 100644 index 0000000..0e0bb12 --- /dev/null +++ b/syntax/python.vim @@ -0,0 +1,374 @@ +" Vim syntax file +" Language: Python +" Maintainer: Dmitry Vasiliev <[email protected]> +" URL: http://www.hlabs.spb.ru/vim/python.vim +" Last Change: 2010-04-09 +" Filenames: *.py +" Version: 2.6.6 +" +" Based on python.vim (from Vim 6.1 distribution) +" by Neil Schemenauer <[email protected]> +" +" Thanks: +" +" Jeroen Ruigrok van der Werven +" for the idea to highlight erroneous operators +" Pedro Algarvio +" for the patch to enable spell checking only for the right spots +" (strings and comments) +" John Eikenberry +" for the patch fixing small typo +" Caleb Adamantine +" for the patch fixing highlighting for decorators +" Andrea Riciputi +" for the patch with new configuration options + +" +" Options: +" +" For set option do: let OPTION_NAME = 1 +" For clear option do: let OPTION_NAME = 0 +" +" Option names: +" +" For highlight builtin functions and objects: +" python_highlight_builtins +" +" For highlight builtin objects: +" python_highlight_builtin_objs +" +" For highlight builtin funtions: +" python_highlight_builtin_funcs +" +" For highlight standard exceptions: +" python_highlight_exceptions +" +" For highlight string formatting: +" python_highlight_string_formatting +" +" For highlight str.format syntax: +" python_highlight_string_format +" +" For highlight string.Template syntax: +" python_highlight_string_templates +" +" For highlight indentation errors: +" python_highlight_indent_errors +" +" For highlight trailing spaces: +" python_highlight_space_errors +" +" For highlight doc-tests: +" python_highlight_doctests +" +" If you want all Python highlightings above: +" python_highlight_all +" (This option not override previously set options) +" +" For fast machines: +" python_slow_sync +" +" For "print" builtin as function: +" python_print_as_function + +" For version 5.x: Clear all syntax items +" For version 6.x: Quit when a syntax file was already loaded +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +if exists("python_highlight_all") && python_highlight_all != 0 + " Not override previously set options + if !exists("python_highlight_builtins") + if !exists("python_highlight_builtin_objs") + let python_highlight_builtin_objs = 1 + endif + if !exists("python_highlight_builtin_funcs") + let python_highlight_builtin_funcs = 1 + endif + endif + if !exists("python_highlight_exceptions") + let python_highlight_exceptions = 1 + endif + if !exists("python_highlight_string_formatting") + let python_highlight_string_formatting = 1 + endif + if !exists("python_highlight_string_format") + let python_highlight_string_format = 1 + endif + if !exists("python_highlight_string_templates") + let python_highlight_string_templates = 1 + endif + if !exists("python_highlight_indent_errors") + let python_highlight_indent_errors = 1 + endif + if !exists("python_highlight_space_errors") + let python_highlight_space_errors = 1 + endif + if !exists("python_highlight_doctests") + let python_highlight_doctests = 1 + endif +endif + +" Keywords +syn keyword pythonStatement break continue del +syn keyword pythonStatement exec return +syn keyword pythonStatement pass raise +syn keyword pythonStatement global assert +syn keyword pythonStatement lambda yield +syn keyword pythonStatement with +syn keyword pythonStatement def class nextgroup=pythonFunction skipwhite +syn match pythonFunction "[a-zA-Z_][a-zA-Z0-9_]*" display contained +syn keyword pythonRepeat for while +syn keyword pythonConditional if elif else +syn keyword pythonPreCondit import from as +syn keyword pythonException try except finally +syn keyword pythonOperator and in is not or + +if !exists("python_print_as_function") || python_print_as_function == 0 + syn keyword pythonStatement print +endif + +" Decorators (new in Python 2.4) +syn match pythonDecorator "@" display nextgroup=pythonDottedName skipwhite +syn match pythonDottedName "[a-zA-Z_][a-zA-Z0-9_]*\(\.[a-zA-Z_][a-zA-Z0-9_]*\)*" display contained +syn match pythonDot "\." display containedin=pythonDottedName + +" Comments +syn match pythonComment "#.*$" display contains=pythonTodo,@Spell +syn match pythonRun "\%^#!.*$" +syn match pythonCoding "\%^.*\(\n.*\)\?#.*coding[:=]\s*[0-9A-Za-z-_.]\+.*$" +syn keyword pythonTodo TODO FIXME XXX contained + +" Errors +syn match pythonError "\<\d\+\D\+\>" display +syn match pythonError "[$?]" display +syn match pythonError "[&|]\{2,}" display +syn match pythonError "[=]\{3,}" display + +" TODO: Mixing spaces and tabs also may be used for pretty formatting multiline +" statements. For now I don't know how to work around this. +if exists("python_highlight_indent_errors") && python_highlight_indent_errors != 0 + syn match pythonIndentError "^\s*\( \t\|\t \)\s*\S"me=e-1 display +endif + +" Trailing space errors +if exists("python_highlight_space_errors") && python_highlight_space_errors != 0 + syn match pythonSpaceError "\s\+$" display +endif + +" Strings +syn region pythonString start=+[bB]\='+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonEscape,pythonEscapeError,@Spell +syn region pythonString start=+[bB]\="+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonEscape,pythonEscapeError,@Spell +syn region pythonString start=+[bB]\="""+ end=+"""+ keepend contains=pythonEscape,pythonEscapeError,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonString start=+[bB]\='''+ end=+'''+ keepend contains=pythonEscape,pythonEscapeError,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonEscape +\\[abfnrtv'"\\]+ display contained +syn match pythonEscape "\\\o\o\=\o\=" display contained +syn match pythonEscapeError "\\\o\{,2}[89]" display contained +syn match pythonEscape "\\x\x\{2}" display contained +syn match pythonEscapeError "\\x\x\=\X" display contained +syn match pythonEscape "\\$" + +" Unicode strings +syn region pythonUniString start=+[uU]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonEscape,pythonUniEscape,pythonEscapeError,pythonUniEscapeError,@Spell +syn region pythonUniString start=+[uU]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonEscape,pythonUniEscape,pythonEscapeError,pythonUniEscapeError,@Spell +syn region pythonUniString start=+[uU]"""+ end=+"""+ keepend contains=pythonEscape,pythonUniEscape,pythonEscapeError,pythonUniEscapeError,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonUniString start=+[uU]'''+ end=+'''+ keepend contains=pythonEscape,pythonUniEscape,pythonEscapeError,pythonUniEscapeError,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonUniEscape "\\u\x\{4}" display contained +syn match pythonUniEscapeError "\\u\x\{,3}\X" display contained +syn match pythonUniEscape "\\U\x\{8}" display contained +syn match pythonUniEscapeError "\\U\x\{,7}\X" display contained +syn match pythonUniEscape "\\N{[A-Z ]\+}" display contained +syn match pythonUniEscapeError "\\N{[^A-Z ]\+}" display contained + +" Raw strings +syn region pythonRawString start=+[rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,@Spell +syn region pythonRawString start=+[rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,@Spell +syn region pythonRawString start=+[rR]"""+ end=+"""+ keepend contains=pythonDocTest2,pythonSpaceError,@Spell +syn region pythonRawString start=+[rR]'''+ end=+'''+ keepend contains=pythonDocTest,pythonSpaceError,@Spell + +syn match pythonRawEscape +\\['"]+ display transparent contained + +" Unicode raw strings +syn region pythonUniRawString start=+[uU][rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,pythonUniRawEscape,pythonUniRawEscapeError,@Spell +syn region pythonUniRawString start=+[uU][rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,pythonUniRawEscape,pythonUniRawEscapeError,@Spell +syn region pythonUniRawString start=+[uU][rR]"""+ end=+"""+ keepend contains=pythonUniRawEscape,pythonUniRawEscapeError,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonUniRawString start=+[uU][rR]'''+ end=+'''+ keepend contains=pythonUniRawEscape,pythonUniRawEscapeError,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonUniRawEscape "\([^\\]\(\\\\\)*\)\@<=\\u\x\{4}" display contained +syn match pythonUniRawEscapeError "\([^\\]\(\\\\\)*\)\@<=\\u\x\{,3}\X" display contained + +if exists("python_highlight_string_formatting") && python_highlight_string_formatting != 0 + " String formatting + syn match pythonStrFormatting "%\(([^)]\+)\)\=[-#0 +]*\d*\(\.\d\+\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString + syn match pythonStrFormatting "%[-#0 +]*\(\*\|\d\+\)\=\(\.\(\*\|\d\+\)\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString +endif + +if exists("python_highlight_string_format") && python_highlight_string_format != 0 + " str.format syntax + syn match pythonStrFormat "{{\|}}" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString + syn match pythonStrFormat "{\([a-zA-Z_][a-zA-Z0-9_]*\|\d\+\)\(\.[a-zA-Z_][a-zA-Z0-9_]*\|\[\(\d\+\|[^!:\}]\+\)\]\)*\(![rs]\)\=\(:\({\([a-zA-Z_][a-zA-Z0-9_]*\|\d\+\)}\|\([^}]\=[<>=^]\)\=[ +-]\=#\=0\=\d*\(\.\d\+\)\=[bcdeEfFgGnoxX%]\=\)\=\)\=}" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString +endif + +if exists("python_highlight_string_templates") && python_highlight_string_templates != 0 + " String templates + syn match pythonStrTemplate "\$\$" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString + syn match pythonStrTemplate "\${[a-zA-Z_][a-zA-Z0-9_]*}" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString + syn match pythonStrTemplate "\$[a-zA-Z_][a-zA-Z0-9_]*" contained containedin=pythonString,pythonUniString,pythonRawString,pythonUniRawString +endif + +if exists("python_highlight_doctests") && python_highlight_doctests != 0 + " DocTests + syn region pythonDocTest start="^\s*>>>" end=+'''+he=s-1 end="^\s*$" contained + syn region pythonDocTest2 start="^\s*>>>" end=+"""+he=s-1 end="^\s*$" contained +endif + +" Numbers (ints, longs, floats, complex) +syn match pythonHexError "\<0[xX]\x*[g-zG-Z]\x*[lL]\=\>" display + +syn match pythonHexNumber "\<0[xX]\x\+[lL]\=\>" display +syn match pythonOctNumber "\<0[oO]\o\+[lL]\=\>" display +syn match pythonBinNumber "\<0[bB][01]\+[lL]\=\>" display + +syn match pythonNumber "\<\d\+[lLjJ]\=\>" display + +syn match pythonFloat "\.\d\+\([eE][+-]\=\d\+\)\=[jJ]\=\>" display +syn match pythonFloat "\<\d\+[eE][+-]\=\d\+[jJ]\=\>" display +syn match pythonFloat "\<\d\+\.\d*\([eE][+-]\=\d\+\)\=[jJ]\=" display + +syn match pythonOctError "\<0[oO]\=\o*[8-9]\d*[lL]\=\>" display +syn match pythonBinError "\<0[bB][01]*[2-9]\d*[lL]\=\>" display + +if exists("python_highlight_builtin_objs") && python_highlight_builtin_objs != 0 + " Builtin objects and types + syn keyword pythonBuiltinObj True False Ellipsis None NotImplemented + syn keyword pythonBuiltinObj __debug__ __doc__ __file__ __name__ __package__ +endif + +if exists("python_highlight_builtin_funcs") && python_highlight_builtin_funcs != 0 + " Builtin functions + syn keyword pythonBuiltinFunc __import__ abs all any apply + syn keyword pythonBuiltinFunc basestring bin bool buffer bytearray bytes callable + syn keyword pythonBuiltinFunc chr classmethod cmp coerce compile complex + syn keyword pythonBuiltinFunc delattr dict dir divmod enumerate eval + syn keyword pythonBuiltinFunc execfile file filter float format frozenset getattr + syn keyword pythonBuiltinFunc globals hasattr hash help hex id + syn keyword pythonBuiltinFunc input int intern isinstance + syn keyword pythonBuiltinFunc issubclass iter len list locals long map max + syn keyword pythonBuiltinFunc min next object oct open ord + syn keyword pythonBuiltinFunc pow property range + syn keyword pythonBuiltinFunc raw_input reduce reload repr + syn keyword pythonBuiltinFunc reversed round set setattr + syn keyword pythonBuiltinFunc slice sorted staticmethod str sum super tuple + syn keyword pythonBuiltinFunc type unichr unicode vars xrange zip + + if exists("python_print_as_function") && python_print_as_function != 0 + syn keyword pythonBuiltinFunc print + endif +endif + +if exists("python_highlight_exceptions") && python_highlight_exceptions != 0 + " Builtin exceptions and warnings + syn keyword pythonExClass BaseException + syn keyword pythonExClass Exception StandardError ArithmeticError + syn keyword pythonExClass LookupError EnvironmentError + + syn keyword pythonExClass AssertionError AttributeError BufferError EOFError + syn keyword pythonExClass FloatingPointError GeneratorExit IOError + syn keyword pythonExClass ImportError IndexError KeyError + syn keyword pythonExClass KeyboardInterrupt MemoryError NameError + syn keyword pythonExClass NotImplementedError OSError OverflowError + syn keyword pythonExClass ReferenceError RuntimeError StopIteration + syn keyword pythonExClass SyntaxError IndentationError TabError + syn keyword pythonExClass SystemError SystemExit TypeError + syn keyword pythonExClass UnboundLocalError UnicodeError + syn keyword pythonExClass UnicodeEncodeError UnicodeDecodeError + syn keyword pythonExClass UnicodeTranslateError ValueError VMSError + syn keyword pythonExClass WindowsError ZeroDivisionError + + syn keyword pythonExClass Warning UserWarning BytesWarning DeprecationWarning + syn keyword pythonExClass PendingDepricationWarning SyntaxWarning + syn keyword pythonExClass RuntimeWarning FutureWarning + syn keyword pythonExClass ImportWarning UnicodeWarning +endif + +if exists("python_slow_sync") && python_slow_sync != 0 + syn sync minlines=2000 +else + " This is fast but code inside triple quoted strings screws it up. It + " is impossible to fix because the only way to know if you are inside a + " triple quoted string is to start from the beginning of the file. + syn sync match pythonSync grouphere NONE "):$" + syn sync maxlines=200 +endif + +if version >= 508 || !exists("did_python_syn_inits") + if version <= 508 + let did_python_syn_inits = 1 + command -nargs=+ HiLink hi link <args> + else + command -nargs=+ HiLink hi def link <args> + endif + + HiLink pythonStatement Statement + HiLink pythonPreCondit Statement + HiLink pythonFunction Function + HiLink pythonConditional Conditional + HiLink pythonRepeat Repeat + HiLink pythonException Exception + HiLink pythonOperator Operator + + HiLink pythonDecorator Define + HiLink pythonDottedName Function + HiLink pythonDot Normal + + HiLink pythonComment Comment + HiLink pythonCoding Special + HiLink pythonRun Special + HiLink pythonTodo Todo + + HiLink pythonError Error + HiLink pythonIndentError Error + HiLink pythonSpaceError Error + + HiLink pythonString String + HiLink pythonUniString String + HiLink pythonRawString String + HiLink pythonUniRawString String + + HiLink pythonEscape Special + HiLink pythonEscapeError Error + HiLink pythonUniEscape Special + HiLink pythonUniEscapeError Error + HiLink pythonUniRawEscape Special + HiLink pythonUniRawEscapeError Error + + HiLink pythonStrFormatting Special + HiLink pythonStrFormat Special + HiLink pythonStrTemplate Special + + HiLink pythonDocTest Special + HiLink pythonDocTest2 Special + + HiLink pythonNumber Number + HiLink pythonHexNumber Number + HiLink pythonOctNumber Number + HiLink pythonBinNumber Number + HiLink pythonFloat Float + HiLink pythonOctError Error + HiLink pythonHexError Error + HiLink pythonBinError Error + + HiLink pythonBuiltinObj Structure + HiLink pythonBuiltinFunc Function + + HiLink pythonExClass Structure + + delcommand HiLink +endif + +let b:current_syntax = "python"
theflow/deployed_at
d9304ce332f4e8327160ccf18ad55d563779fde2
make created_at a parameter in the API
diff --git a/deployed_at.rb b/deployed_at.rb index 893a8a2..3132556 100644 --- a/deployed_at.rb +++ b/deployed_at.rb @@ -1,255 +1,255 @@ require 'rubygems' require 'sinatra' require 'dm-core' -require 'dm-timestamps' require 'net/smtp' DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/database.sqlite3") enable :sessions class Deploy include DataMapper::Resource property :id, Integer, :serial => true property :title, String property :user, String property :head_rev, String property :current_rev, String property :changes, Integer, :default => 0 property :scm_log, Text property :project_id, Integer property :created_at, DateTime belongs_to :project before :save, :set_number_of_changes before :save, :set_proper_title after :save, :notify def set_proper_title self.title = "Deploy of revision #{head_rev}" if title.blank? end def set_number_of_changes self.changes = get_number_of_changes end def get_number_of_changes scm_log.blank? ? 0 : scm_log.scan(/^r\d+/).size end def notify DeployMailer.send(project, current_rev, head_rev, scm_log) end def month created_at.strftime('%Y-%m') end def self.in_month(year_month) year, month = year_month.split('-') next_month = "#{year}-%02i" % (month.to_i + 1) all(:created_at.gte => year_month, :created_at.lt => next_month, :order => [:created_at.desc]) end end class Project include DataMapper::Resource property :id, Integer, :serial => true property :name, String has n, :deploys has n, :subscriptions has n, :users, :through => :subscriptions def all_deploys_grouped_by_date deploys.all(:order => [:created_at.desc]).inject({}) do |groups, deploy| (groups[deploy.month] ||= []) << deploy groups end end def self.find_or_create(name) project = self.first(:name => name) project || self.create(:name => name) end end class User include DataMapper::Resource property :id, Integer, :serial => true property :email, String has n, :subscriptions has n, :projects, :through => :subscriptions def manage_subscriptions(param_hash) subscriptions.clear subscriptions.save param_hash.keys.each do |project_id| subscriptions.create(:project_id => project_id) end end def self.find_or_create(email) first(:email => email) || create(:email => email) end end class Subscription include DataMapper::Resource property :id, Integer, :serial => true belongs_to :project belongs_to :user end class DeployMailer class << self attr_accessor :config end def self.send(project, current_rev, head_rev, svn_log) recipients = project.users.map { |u| u.email } return if recipients.empty? message_body = format_msg(project.name, current_rev, head_rev, svn_log) send_by_smtp(message_body, 'DeployedAt <[email protected]>', recipients) end def self.send_by_smtp(body, from, to) Net::SMTP.start(config[:host], config[:port], 'localhost', config[:user], config[:pass], config[:auth]) do |smtp| smtp.send_message(body, from, to) end end def self.format_msg(project_name, current_rev, head_rev, svn_log) msg = <<END_OF_MESSAGE From: DeployedIt <[email protected]> To: DeployedIt <[email protected]> Subject: [DeployedIt] #{project_name} deploy * Deployment started at #{Time.now} * Changes in this deployment: #{svn_log} END_OF_MESSAGE end end CONFIG_FILE = File.join(File.dirname(__FILE__), 'config.yml') if File.exist?(CONFIG_FILE) DeployMailer.config = YAML::load_file(CONFIG_FILE)['smtp_settings'] else puts ' Please create a config file by copying the example config:' puts ' $ cp config.example.yml config.yml' exit end DataMapper.auto_upgrade! get '/' do @deploys = Deploy.all(:order => [:created_at.desc], :limit => 15) @title = 'Recent deploys' erb :dashboard end get '/projects/:id' do @project = Project.get(params[:id]) if params[:show] @last_deploys = @project.deploys.in_month(params[:show]) else @last_deploys = @project.deploys.all(:order => [:created_at.desc], :limit => 10) end @grouped_deploys = @project.all_deploys_grouped_by_date @years = @grouped_deploys.keys.map { |month| month.split('-').first }.uniq.sort.reverse @title = "Recent deploys for #{@project.name}" erb :deploys_list end get '/deploys/:id' do @deploy = Deploy.get(params[:id]) @project = @deploy.project @title = "[#{@project.name}] #{@deploy.title}" erb :deploys_show end post '/deploys' do project = Project.find_or_create(params[:project]) project.deploys.create(:title => params[:title], :user => params[:user], :scm_log => params[:scm_log], :head_rev => params[:head_rev], - :current_rev => params[:current_rev]) + :current_rev => params[:current_rev], + :created_at => params[:date] || Time.now) end get '/session' do @title = 'Log in' erb :session_show end post '/session' do redirect '/session' and return if params[:email].blank? user = User.find_or_create(params[:email]) session[:user_id] = user.id redirect '/subscriptions' end get '/subscriptions' do redirect '/session' and return if logged_out? @subscribed_projects = current_user.projects @title = 'Your subscriptions' erb :subscriptions_list end post '/subscriptions' do redirect '/session' and return if logged_out? current_user.manage_subscriptions(params) redirect 'subscriptions' end before do @projects = Project.all if request.get? end helpers do def logged_out? session[:user_id].blank? end def current_user @user ||= User.get(session[:user_id]) end def format_time(time) time.strftime('%b %d %H:%M') end def link_to_month(month_name, month, project, grouped_deploys) number_of_deploys = grouped_deploys.has_key?(month) ? grouped_deploys[month].size : 0 if number_of_deploys == 0 "<span class=\"quiet\">#{month_name}</span>" else "<a href=\"/projects/#{project.id}?show=#{month}\">#{month_name}</a> <small>(#{number_of_deploys})</small>" end end end