code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
public class HundredIntegers {
public static void main (String[] args) {
for (int i = 1; i<=100; i++) {
System.out.println(i);
}
}
}
|
100integers
|
HundredIntegers.java
|
Java
|
epl
| 147
|
public class HundredIntegers {
public static void main (String[] args) {
for (int i = 1; i<=100; i++) {
System.out.println(i);
}
}
}
|
100integers
|
trunk/HundredIntegers.java
|
Java
|
epl
| 147
|
package Entity;
public interface IOperatoerDTO {
int getoprId();
void setoprId(int Id);
String getoprNavn();
void setoprNavn(String Navn);
String getini();
void setini(String In);
String getcpr();
void setcpr(String cp);
String getpassword();
void setpassword(String passwd);
}
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Entity/IOperatoerDTO.java
|
Java
|
epl
| 325
|
package Entity;
public class OperatoerDTO implements IOperatoerDTO
{
int oprId;
String oprNavn;
String ini;
String cpr;
String password;
public OperatoerDTO() //Default Constructor
{
this.oprId = 0;
this.oprNavn = "";
this.ini = "";
this.cpr = "";
this.password = "";
}
public OperatoerDTO (int oId, String oNavn, String i, String cr, String pwd) //created constructor
{
this.oprId = oId;
this.oprNavn = oNavn;
this.ini = i;
this.cpr = cr;
this.password = pwd;
}
public int getoprId(){
return oprId;} //return must be oprId not 0;
public void setoprId(int Id){
oprId = Id;
}
public String getoprNavn(){
return oprNavn;
}
public void setoprNavn(String Navn){
oprNavn = Navn;
}
public String getini(){
return ini;
}
public void setini(String In){
ini = In;
}
public String getcpr(){
return cpr;
}
public void setcpr(String cp){
cpr = cp;
}
public String getpassword(){
return password;
}
public void setpassword(String passwd){
password = passwd;
}
}//corrected setters and getters
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Entity/OperatoerDTO.java
|
Java
|
epl
| 1,149
|
package Controller;
import Entity.OperatoerDTO;
/*
public class ChangePassword implements IOperatoerDAO {
OperatoerDTO opr = new OperatoerDTO();
public String passwordGenerator(String passwd){
return passwd;
}
public String opChangePasswd(int Id)
{
return null;
}
*/
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/ChangePassword.java
|
Java
|
epl
| 300
|
package Controller;
import java.util.ArrayList;
import Entity.OperatoerDTO;
public class OperatoerDAO implements IOperatoerDAO{
OperatoerDTO opr = new OperatoerDTO();
private ArrayList<OperatoerDTO> oDTO = new ArrayList<OperatoerDTO>();; //added an arraylist of type OperatoerDTO
public OperatoerDAO()
{
}
public OperatoerDTO getOperatoer(int oprId) throws DALException{
return opr;
}
public ArrayList<OperatoerDTO> getOperatoerList() throws DALException
{
return oDTO;
}
public void createOperatoer(OperatoerDTO opr) throws DALException{
oDTO.add(opr);
}
public void updateOperatoer(OperatoerDTO opr) throws DALException{}
}
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/OperatoerDAO.java
|
Java
|
epl
| 682
|
package Controller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/*
* Validate password with regular expression
* @param password password for validation
* @return true valid password, false invalid password
*/
public boolean validate(String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
}
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/PasswordValidator.java
|
Java
|
epl
| 702
|
package Controller;
import Entity.OperatoerDTO;
/*
public class LoginTjeck implements IOperatoerDAO {
OperatoerDTO opr = new OperatoerDTO();
public int loginUser(String passwd, int id)
{
return 0;
}
}*/
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/LoginTjeck.java
|
Java
|
epl
| 229
|
package Controller;
import Entity.OperatoerDTO;
/*
public class Afvejning implements IOperatoerDAO {
OperatoerDTO opr = new OperatoerDTO();
public double beregningNetto(double Tara, double Brutto)
{
return 0.0;
}
}*/
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/Afvejning.java
|
Java
|
epl
| 243
|
package Controller;
import Entity.OperatoerDTO;
import java.util.ArrayList;
public interface IOperatoerDAO
{
//int loginUser(String passwd, int id);
OperatoerDTO getOperatoer(int oprId) throws DALException;
ArrayList<OperatoerDTO> getOperatoerList() throws DALException;
void createOperatoer(OperatoerDTO opr) throws DALException;
void updateOperatoer(OperatoerDTO opr) throws DALException;
// String passwordGenerator(String passwd);
// String opchangepasswd(int Id);
//double beregningNetto(double Tara, double Brutto);
public class DALException extends Exception //added exception class
{
public DALException()
{
super( " findes ikke.");
}
}
}
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/IOperatoerDAO.java
|
Java
|
epl
| 706
|
package Boundary;
import Entity.OperatoerDTO;
import Controller.IOperatoerDAO.DALException;
import Controller.OperatoerDAO;
import Controller.PasswordValidator;
import java.util.Scanner;
public class Graenseflade {
OperatoerDTO opr = new OperatoerDTO();
OperatoerDAO dao = new OperatoerDAO();
PasswordValidator pv = new PasswordValidator();
boolean go = true;
public Graenseflade() //added user options
{
while(go){
System.out.println("1. Login");
System.out.println("2. Change Password");
System.out.println("3. Exit");
System.out.println("Enter your choice");
Scanner sc = new Scanner(System.in); //user input
String choice = sc.next();
switch(choice) //checking admin login
{
case "1":
Scanner user = new Scanner(System.in);
System.out.println("Enter ID:");
String uname = user.next();
System.out.println("Enter password:");
String pwd = user.next();
if((uname.equals("BOB")) && (pwd.equals("DGMNZ123")))
{
System.out.println("Login Successful");
System.out.println();
System.out.println("Select you choice");
System.out.println("1. Create Operator");
System.out.println("2. Udpate Operator");
System.out.println("3. Delete Operator");
}
//Scanner s = new Scanner(System.in); //user input
String ch = sc.next();
switch(ch) //Admin entering operator data
{
case "1":
Scanner admin = new Scanner(System.in);
System.out.println("Enter ID");
int ID = admin.nextInt();
opr.setoprId(ID);
System.out.println("Enter Name");
String name = admin.next();
opr.setoprNavn(name);
System.out.println("Enter CPR");
String cpr = admin.next();
opr.setcpr(cpr);
System.out.println("Enter Password");
/*
must contains one digit from 0-9
must contains one lowercase characters
must contains one uppercase characters
must contains one special symbols in the list "@#$%"
match anything with previous condition checking
length at least 6 characters and maximum of 20
*/
String pass = admin.next();
while((pv.validate(pass)) == false)
{
System.out.println("Enter a new Password");
pass = admin.next();
}
opr.setpassword(pass);
try { //try catch for createOperatoer
dao.createOperatoer(opr);
} catch (DALException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case "3":
System.exit(0);;
}
System.out.println("Id: " + opr.getoprId() + "\nName: " + opr.getoprNavn()
+ "\nCPR: " + opr.getcpr() + "\nPassword: " + opr.getpassword());
System.out.println();
}
}
//Login interface
/* if(Id == 10 && passwd == "02304it")
{
int Id = sysadminInt();
}
*/
//Operatorinterface
//Sysadmininterface
/* private int sysadminInt()
{
return 0;
}
*/
//vægtdetaljerinterface
}
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Boundary/Graenseflade.java
|
Java
|
epl
| 3,119
|
import Boundary.Graenseflade;
public class Main {
public static void main(String[] args) {
Graenseflade g = new Graenseflade();
}
}
|
02324cdio-del1
|
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Main.java
|
Java
|
epl
| 140
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Moog-like low pass audio filter.
*/
goog.provide('doodle.moog.LowPassFilter');
goog.require('doodle.moog.CompoundAudioNode');
/**
* A dynamic low pass filter emulator.
* @param {!AudioContext} audioContext Audio context to which this oscillator
* will be bound.
* @param {number} cutoffFrequency The cutoff frequency above which the
* frequencies are attenuated.
* @param {number} contour Amount of contour to apply to the filter envelope.
* @param {number} attackTime Initial attack time in seconds.
* @param {number} decayTime Initial decay time in seconds.
* @param {number} sustainLevel Initial sustain level [0..1].
* @constructor
* @implements {doodle.moog.CompoundAudioNode}
*/
doodle.moog.LowPassFilter = function(
audioContext, cutoffFrequency, contour, attackTime, decayTime,
sustainLevel) {
/**
* Audio context in which this filter operates.
* @type {!AudioContext}
* @private
*/
this.audioContext_ = audioContext;
/**
* The low pass filter Web Audio node.
* @type {!BiquadFilterNode}
* @private
*/
this.lowPassFilterNode_ = audioContext.createBiquadFilter();
this.lowPassFilterNode_.type =
doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_;
/**
* Frequency above which sound should be progressively attenuated.
* @type {number}
* @private
*/
this.cutoffFrequency_ = cutoffFrequency;
/**
* The amount of 'contour' to add to the low pass filter ADS (attack, decay,
* sustain) envelope. Contour is essentially a variable cutoff frequency
* coefficient. See doodle.moog.EnvelopeGenerator for an explanation of how
* ADS envelopes work.
* @type {number}
* @private
*/
this.contour_ = contour;
/**
* The duration of the attack phase in seconds.
* @type {number}
* @private
*/
this.attackTime_ = attackTime;
/**
* The duration of the decay phase in seconds.
* @type {number}
* @private
*/
this.decayTime_ = decayTime;
/**
* The sustain frequency coefficient.
* @type {number}
* @private
*/
this.sustainLevel_ = sustainLevel;
this.resetContourEnvelope_();
};
/**
* Biquad Filter type ID for a low pass filter (from the Web Audio spec).
* @type {number}
* @const
* @private
*/
doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0;
/**
* Initiates the attack phase of the contour envelope (e.g., when a key is
* pressed).
*/
doodle.moog.LowPassFilter.prototype.startAttack = function() {
var now = this.audioContext_.currentTime;
this.lowPassFilterNode_.frequency.cancelScheduledValues(now);
this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_;
this.lowPassFilterNode_.frequency.setValueAtTime(this.cutoffFrequency_, now);
var contourFrequency = this.contour_ * this.cutoffFrequency_;
this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime(
contourFrequency, now + this.attackTime_);
this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime(
this.cutoffFrequency_ +
this.sustainLevel_ * (contourFrequency - this.cutoffFrequency_),
now + this.attackTime_ + this.decayTime_);
};
/**
* Sets the filter cutoff frequency.
* @param {number} cutoffFrequency The cutoff frequency above which the
* frequencies are attenuated.
*/
doodle.moog.LowPassFilter.prototype.setCutoffFrequency = function(
cutoffFrequency) {
this.cutoffFrequency_ = cutoffFrequency;
this.resetContourEnvelope_();
};
/**
* Sets the filter envelope contour.
* @param {number} contour Amount of contour to apply to the filter envelope.
*/
doodle.moog.LowPassFilter.prototype.setContour = function(contour) {
this.contour_ = contour;
this.resetContourEnvelope_();
};
/**
* Sets attack phase duration.
* @param {number} time Duration of the attack phase in seconds.
*/
doodle.moog.LowPassFilter.prototype.setContourAttackTime = function(time) {
this.attackTime_ = time;
this.resetContourEnvelope_();
};
/**
* Sets decay phase duration.
* @param {number} time Duration of the decay phase in seconds.
*/
doodle.moog.LowPassFilter.prototype.setContourDecayTime = function(time) {
this.decayTime_ = time;
this.resetContourEnvelope_();
};
/**
* Sets the sustain level.
* @param {number} level The sustain level, a number in the range [0, 1].
*/
doodle.moog.LowPassFilter.prototype.setContourSustainLevel = function(level) {
this.sustainLevel_ = level;
this.resetContourEnvelope_();
};
/**
* Resets the contour envelope AudioParam using current LowPassFilter state.
* @private
*/
doodle.moog.LowPassFilter.prototype.resetContourEnvelope_ = function() {
this.lowPassFilterNode_.frequency.cancelScheduledValues(0);
this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_;
};
/** @inheritDoc */
doodle.moog.LowPassFilter.prototype.getSourceNode = function() {
return this.lowPassFilterNode_;
};
/** @inheritDoc */
doodle.moog.LowPassFilter.prototype.connect = function(destination) {
this.lowPassFilterNode_.connect(destination);
};
/** @inheritDoc */
doodle.moog.LowPassFilter.prototype.disconnect = function() {
this.lowPassFilterNode_.disconnect();
};
|
010pepe010-moog
|
low_pass_filter.js
|
JavaScript
|
asf20
| 5,777
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.addDependency('../../../compound_audio_node.js', ['doodle.moog.CompoundAudioNode'], []);
goog.addDependency('../../../envelope_generator.js', ['doodle.moog.EnvelopeGenerator'], []);
goog.addDependency('../../../low_pass_filter.js', ['doodle.moog.LowPassFilter'], ['doodle.moog.CompoundAudioNode']);
goog.addDependency('../../../master_mixer.js', ['doodle.moog.MasterMixer'], ['doodle.moog.MasterMixerInterface']);
goog.addDependency('../../../master_mixer_interface.js', ['doodle.moog.MasterMixerInterface'], []);
goog.addDependency('../../../moog.js', ['doodle.moog.Moog'], ['doodle.moog.LowPassFilter', 'doodle.moog.MasterMixer', 'doodle.moog.Oscillator', 'doodle.moog.OscillatorInterface', 'doodle.moog.Synthesizer', 'doodle.moog.WideBandPassFilter', 'goog.Disposable']);
goog.addDependency('../../../oscillator.js', ['doodle.moog.Oscillator'], ['doodle.moog.EnvelopeGenerator', 'doodle.moog.OscillatorInterface']);
goog.addDependency('../../../oscillator_interface.js', ['doodle.moog.OscillatorInterface', 'doodle.moog.OscillatorInterface.FillMode', 'doodle.moog.OscillatorInterface.Range', 'doodle.moog.OscillatorInterface.WaveForm'], []);
goog.addDependency('../../../synthesizer.js', ['doodle.moog.Synthesizer'], ['doodle.moog.CompoundAudioNode', 'doodle.moog.OscillatorInterface', 'doodle.moog.SynthesizerInterface', 'goog.array', 'goog.userAgent']);
goog.addDependency('../../../synthesizer_interface.js', ['doodle.moog.SynthesizerInterface'], []);
goog.addDependency('../../../wide_band_pass_filter.js', ['doodle.moog.WideBandPassFilter'], ['doodle.moog.CompoundAudioNode']);
|
010pepe010-moog
|
deps.js
|
JavaScript
|
asf20
| 2,201
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Voltage controlled oscillator emulators.
*/
goog.provide('doodle.moog.OscillatorInterface');
goog.provide('doodle.moog.OscillatorInterface.FillMode');
goog.provide('doodle.moog.OscillatorInterface.Range');
goog.provide('doodle.moog.OscillatorInterface.WaveForm');
/**
* Oscillator interface to be implemented in WebAudio and FlashAudio.
* @interface
*/
doodle.moog.OscillatorInterface = function() {};
/**
* Different methods in which an oscillator can fill an audio buffer.
* @enum {number}
*/
doodle.moog.OscillatorInterface.FillMode = {
// Clobber any pre-existing data in the buffer.
CLOBBER: 0,
// Add signal to the buffer.
ADD: 1,
// Add signal to the buffer and then do an even mix down.
MIX: 2
};
/**
* Different 'ranges' (i.e., octaves in synth lingo) in which an oscillator can
* generate a tone. 'LO' is a special Moog-ism that generates sub-audio clicks
* and pops.
* @enum {number}
*/
doodle.moog.OscillatorInterface.Range = {
LO: 0.0625,
R32: 2,
R16: 4,
R8: 8,
R4: 16,
R2: 32
};
/**
* Different wave forms that can be generated by an oscillator, each of which
* has a different overtone spectrum leading to a different base timbre.
* @enum {number}
*/
doodle.moog.OscillatorInterface.WaveForm = {
TRIANGLE: 0,
SAWANGLE: 1,
RAMP: 2,
REVERSE_RAMP: 3,
SQUARE: 4,
FAT_PULSE: 5,
PULSE: 6
};
/**
* Sets the volume on this oscillator.
* @param {number} volume Volume in the range of [0, 1].
*/
doodle.moog.OscillatorInterface.prototype.setVolume = function(volume) {};
/**
* Sets the wave form generated by this oscillator.
* @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm The wave form to
* use.
*/
doodle.moog.OscillatorInterface.prototype.setWaveForm = function(waveForm) {};
/**
* Sets the pitch bend on this oscillator.
* @param {number} pitchBend Pitch bend amount in the range of [-1, 1].
*/
doodle.moog.OscillatorInterface.prototype.setPitchBend = function(pitchBend) {};
/**
* Sets the octave/range of this oscillator.
* @param {!doodle.moog.OscillatorInterface.Range} range The range of this
* oscillator.
*/
doodle.moog.OscillatorInterface.prototype.setRange = function(range) {};
/**
* Turns on keyboard pitch control.
*/
doodle.moog.OscillatorInterface.prototype.turnOnKeyboardPitchControl =
function() {};
/**
* Turns off keyboard pitch control.
*/
doodle.moog.OscillatorInterface.prototype.turnOffKeyboardPitchControl =
function() {};
/**
* Turns on frequency modulation.
*/
doodle.moog.OscillatorInterface.prototype.turnOnFrequencyModulation =
function() {};
/**
* Turns off frequency modulation.
*/
doodle.moog.OscillatorInterface.prototype.turnOffFrequencyModulation =
function() {};
/**
* Sets the modulation signal level.
* @param {number} modulatorLevel If a modulator, how strong the modulator
* control signal should be [0..1].
*/
doodle.moog.OscillatorInterface.prototype.setModulatorLevel =
function(modulatorLevel) {};
/**
* Turns on glide.
*/
doodle.moog.OscillatorInterface.prototype.turnOnGlide = function() {};
/**
* Turns off glide.
*/
doodle.moog.OscillatorInterface.prototype.turnOffGlide = function() {};
/**
* Sets the duration of gliding.
* @param {number} time The time to glide between notes in seconds.
*/
doodle.moog.OscillatorInterface.prototype.setGlideDuration = function(time) {};
/**
* Sets the note this oscillator should generate.
* @param {number} note Chromatic index of the note to be played relative to the
* beginning of the keyboard.
*/
doodle.moog.OscillatorInterface.prototype.setActiveNote = function(note) {};
/**
* Sets the attack time for this oscillator's envelope generator.
* @param {number} attackTime The new attack time.
*/
doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorAttackTime =
function(attackTime) {};
/**
* Sets the decay time for this oscillator's envelope generator.
* @param {number} decayTime The new decay time.
*/
doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorDecayTime =
function(decayTime) {};
/**
* Sets the sustain level for this oscillator's envelope generator.
* @param {number} sustainLevel The new sustain level.
*/
doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorSustainLevel =
function(sustainLevel) {};
|
010pepe010-moog
|
oscillator_interface.js
|
JavaScript
|
asf20
| 4,979
|
<!doctype html>
<!--
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
-->
<html>
<head>
<meta charset="utf-8">
<title>Moog JS Demo</title>
<style type="text/css">
#keyboard > button {
background-color: #eee;
border: 2px solid black;
cursor: pointer;
font-weight: bold;
height: 50px;
width: 50px;
}
</style>
</head>
<body>
<h1>Moog Doodle Demo Page</h1>
To get this running:
<ul>
<li>If you got this code by:
<ul>
<li>tarball/zip, then download
<a href="http://code.google.com/p/closure-library/source/browse/#svn%2Ftrunk">Closure
Library</a> to a folder named 'closure' in this directory.</li>
<li>git clone, then run
<code>git submodule init && git submodule update</code></li>
</ul>
</li>
<li>Make sure volume is unmuted, speakers are on, etc.</li>
<li>Open this file in a Web Audio enabled browser like Chrome.</li>
<li>Press the buttons below to play tones.</li>
</ul>
<h2>Keys</h2>
<div id=keyboard>
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
</div>
<h2>Cutoff Frequency</h2>
<input id=cutoff type=range min=20 max=5000 value=2100 style=width:500px>
<script src="closure/closure/goog/base.js"></script>
<script src="closure/closure/goog/deps.js"></script>
<script src="deps.js"></script>
<script>
goog.require('doodle.moog.Moog');
window.onload = function() {
var moog = new doodle.moog.Moog();
moog.turnOnAudio();
var keyboard = document.getElementById('keyboard');
keyboard.addEventListener('mousedown', function(e) {
if (e.target.tagName == 'BUTTON') {
moog.synthesizers_[0].setKeyDown(parseInt(e.target.innerHTML, 10));
}
}, false);
keyboard.addEventListener('mouseup', function(e) {
moog.synthesizers_[0].setKeyUp();
}, false);
keyboard.addEventListener('mouseout', function(e) {
moog.synthesizers_[0].setKeyUp();
}, false);
var cutoff = document.getElementById('cutoff');
cutoff.addEventListener('change', function() {
moog.synthesizers_[0].lowPassFilter.setCutoffFrequency(cutoff.value);
}, false);
};
</script>
</body>
</html>
|
010pepe010-moog
|
demo.html
|
HTML
|
asf20
| 2,825
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A moog-like audio synthesizer built on top of the HTML5 Web
* Audio API.
*/
goog.provide('doodle.moog.Synthesizer');
goog.require('doodle.moog.CompoundAudioNode');
goog.require('doodle.moog.OscillatorInterface');
goog.require('doodle.moog.SynthesizerInterface');
goog.require('goog.array');
goog.require('goog.userAgent');
/**
* A Moog-like synthesizer built on top of the HTML5 Web Audio API.
* @param {!AudioContext} audioContext Audio context in which this synthesizer
* will operate.
* @param {!Array.<!doodle.moog.Oscillator>} oscillators The oscillators used
* within this synthesizer.
* @param {!doodle.moog.LowPassFilter} lowPassFilter The low pass filter used
* within this synthesizer.
* @param {number} volume How much the gain should be adjusted.
* @implements {doodle.moog.CompoundAudioNode}
* @implements {doodle.moog.SynthesizerInterface}
* @constructor
*/
doodle.moog.Synthesizer = function(
audioContext, oscillators, lowPassFilter, volume) {
/**
* The audio context in which this synthesizer operates.
* @type {!AudioContext}
* @private
*/
this.audioContext_ = audioContext;
/**
* Oscillators used to generate synthesizer sounds.
* @type {!Array.<!doodle.moog.Oscillator>}
*/
this.oscillators = oscillators;
/**
* Filter used to cut off high frequencies.
* @type {!doodle.moog.LowPassFilter}
*/
this.lowPassFilter = lowPassFilter;
/**
* The volume Web Audio node.
* @type {!AudioGainNode}
* @private
*/
this.volumeNode_ = audioContext.createGainNode();
/**
* Frequency analyser node.
* @type {!RealtimeAnalyserNode}
*/
this.analyserNode = audioContext.createAnalyser();
this.analyserNode.smoothingTimeConstant = 0.5;
/**
* Volume/gain adjustment to apply to the output signal.
* @type {number}
* @private
*/
this.volume_;
this.setVolume(volume);
/**
* Web Audio JavaScript node used by oscillators to generate sound.
* Chrome 20+ won't connect a js node with no inputs for some reason.
* @type {!JavaScriptAudioNode}
* @private
*/
this.jsAudioNode_ = goog.userAgent.isVersion('20.0') ?
audioContext.createJavaScriptNode(
doodle.moog.Synthesizer.BUFFER_SIZE_, 1, 1) :
audioContext.createJavaScriptNode(
doodle.moog.Synthesizer.BUFFER_SIZE_, 0, 1);
this.jsAudioNode_.onaudioprocess = goog.bind(this.fillAudioBuffer_, this);
this.jsAudioNode_.connect(this.lowPassFilter.getSourceNode());
this.lowPassFilter.connect(this.volumeNode_);
this.volumeNode_.connect(this.analyserNode);
};
/**
* How many samples to fill at a time in a JavaScript audio node callback. A
* larger number here will decrease the chance of jitters/gaps at the expense of
* control latency.
* @type {number}
* @const
* @private
*/
doodle.moog.Synthesizer.BUFFER_SIZE_ = 1024;
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setKeyDown = function(note) {
goog.array.forEach(this.oscillators, function(oscillator) {
oscillator.setActiveNote(note);
oscillator.envelopeGenerator.startAttack();
});
this.lowPassFilter.startAttack();
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setKeyDownCallback = function(callback) {
// No-op, since this is only required on non-WebAudio browsers.
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setKeyUp = function() {
goog.array.forEach(this.oscillators, function(oscillator) {
oscillator.envelopeGenerator.startRelease();
});
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpCutoffFrequency =
function(cutoffFrequency) {
this.lowPassFilter.setCutoffFrequency(cutoffFrequency);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContour = function(contour) {
this.lowPassFilter.setContour(contour);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContourAttackTime = function(time) {
this.lowPassFilter.setContourAttackTime(time);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContourDecayTime = function(time) {
this.lowPassFilter.setContourDecayTime(time);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContourSustainLevel = function(level) {
this.lowPassFilter.setContourSustainLevel(level);
};
/**
* Fills the passed audio buffer with tones generated by oscillators.
* @param {!AudioProcessingEvent} e The audio process event object.
* @private
*/
doodle.moog.Synthesizer.prototype.fillAudioBuffer_ = function(e) {
// NOTE: We fill oscillator 2 first since it generates a modulation control
// signal on which oscillators 0 and 1 depend.
this.oscillators[2].fillAudioBuffer(
e, null, doodle.moog.OscillatorInterface.FillMode.CLOBBER);
this.oscillators[0].fillAudioBuffer(
e, this.oscillators[2].modulatorSignal,
doodle.moog.OscillatorInterface.FillMode.ADD);
this.oscillators[1].fillAudioBuffer(
e, this.oscillators[2].modulatorSignal,
doodle.moog.OscillatorInterface.FillMode.MIX, this.oscillators.length);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setVolume = function(volume) {
this.volume_ = volume;
this.volumeNode_.gain.value = volume;
};
/** @override */
doodle.moog.Synthesizer.prototype.getSourceNode = function() {
return this.jsAudioNode_;
};
/** @override */
doodle.moog.Synthesizer.prototype.connect = function(destination) {
this.analyserNode.connect(destination);
};
/** @override */
doodle.moog.Synthesizer.prototype.disconnect = function() {
this.analyserNode.disconnect();
};
|
010pepe010-moog
|
synthesizer.js
|
JavaScript
|
asf20
| 6,169
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Attack, Decay, Sustain, Decay (ADSD) envelope generator.
*/
goog.provide('doodle.moog.EnvelopeGenerator');
/**
* An ADSD envelope generator, used to control volume of a single synth note.
*
* See the Phase_ enum below for a description of how ADSD envelopes work.
*
* @param {number} sampleInterval How many seconds pass with each sample.
* @param {number} attackTime Initial attack time in seconds.
* @param {number} decayTime Initial decay time in seconds.
* @param {number} sustainLevel Initial sustain level [0..1].
* @constructor
*/
doodle.moog.EnvelopeGenerator = function(
sampleInterval, attackTime, decayTime, sustainLevel) {
/**
* How many seconds pass with each sample.
* @type {number}
* @private
* @const
*/
this.SAMPLE_INTERVAL_ = sampleInterval;
/**
* The amount by which the tone associated with this envelope should be
* scaled. A number in the range [0, 1].
* @type {number}
* @private
*/
this.amplitudeCoefficient_ = 0;
/**
* The current phase of the envelope.
* @type {!doodle.moog.EnvelopeGenerator.Phase_}
* @private
*/
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE;
/**
* The duration of the attack phase in seconds.
* @type {number}
* @private
*/
this.attackTime_ = attackTime;
/**
* How much the amplitude should be increased for each sample in the attack
* phase.
*
* NOTE: This variable and other 'step' variables can be computed from other
* EnvelopeGenerator state. We explicitly store these values though since
* they are precisely the data needed in getNextAmplitudeCoefficient which is
* typically executed in a sound buffer filling loop and therefore performance
* critical.
* @type {number}
* @private
*/
this.attackStep_;
/**
* The duration of the decay phase in seconds.
* @type {number}
* @private
*/
this.decayTime_ = decayTime;
/**
* How much the amplitude should be decreased for each sample in the decay
* phase.
* @type {number}
* @private
*/
this.decayStep_;
/**
* The sustain amplitude coefficient.
* @type {number}
* @private
*/
this.sustainLevel_ = sustainLevel;
/**
* How much the amplitude should be decreased for each sample in the release
* phase.
* @type {number}
* @private
*/
this.releaseStep_;
this.recomputePhaseSteps_();
};
/**
* The different phases of an ADSD envelope. When playing a key on a synth,
* these phases are always executed in the order they're defined in this enum.
*
* @enum {number}
* @private
*/
doodle.moog.EnvelopeGenerator.Phase_ = {
// A linear ramp up from no volume (just before a key is struck) to maximum
// volume.
ATTACK: 0,
// A linear ramp down from maximum volume to the sustain volume level.
DECAY: 1,
// Once the attack and decay phases have completed, the volume at which the
// note is held until the key is released.
SUSTAIN: 2,
// A linear ramp down from the sustain volume to no volume after a key is
// released. Moog instruments uniquely reuse the decay time parameter for the
// release time (hence the "ADSD" acronym instead of "ADSR").
RELEASE: 3,
// Meta state indicating that the envelope is not currently active.
INACTIVE: 4
};
/**
* Initiates the attack phase of the envelope (e.g., when a key is pressed).
*/
doodle.moog.EnvelopeGenerator.prototype.startAttack = function() {
this.recomputePhaseSteps_();
this.amplitudeCoefficient_ = 0;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.ATTACK;
};
/**
* Initiates the release phase of the envelope (e.g., when a key is lifted).
*/
doodle.moog.EnvelopeGenerator.prototype.startRelease = function() {
if (this.phase_ == doodle.moog.EnvelopeGenerator.Phase_.RELEASE) {
return;
} else {
// Compute release step based on the current amplitudeCoefficient_.
if (this.decayTime_ <= 0) {
this.releaseStep_ = 1;
} else {
this.releaseStep_ =
this.amplitudeCoefficient_ * this.SAMPLE_INTERVAL_ / this.decayTime_;
}
}
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.RELEASE;
};
/**
* Gets the next amplitude coefficient that should be applied to the currently
* playing note. This method must be called (and applied, natch) for each
* sample filled for the duration of a note.
*
* @return {number} An amplitude coefficient in the range [0, 1] that should be
* applied to the current sample.
*/
doodle.moog.EnvelopeGenerator.prototype.getNextAmplitudeCoefficient =
function() {
switch (this.phase_) {
case doodle.moog.EnvelopeGenerator.Phase_.ATTACK:
this.amplitudeCoefficient_ += this.attackStep_;
if (this.amplitudeCoefficient_ >= 1) {
this.amplitudeCoefficient_ = 1;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.DECAY;
}
break;
case doodle.moog.EnvelopeGenerator.Phase_.DECAY:
this.amplitudeCoefficient_ -= this.decayStep_;
if (this.amplitudeCoefficient_ <= this.sustainLevel_) {
this.amplitudeCoefficient_ = this.sustainLevel_;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN;
}
break;
case doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN:
// Just stay at the sustain level until a release is signaled.
break;
case doodle.moog.EnvelopeGenerator.Phase_.RELEASE:
this.amplitudeCoefficient_ -= this.releaseStep_;
if (this.amplitudeCoefficient_ <= 0) {
this.amplitudeCoefficient_ = 0;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE;
}
break;
case doodle.moog.EnvelopeGenerator.Phase_.INACTIVE:
// Stay at 0, as set in the release transition (muted).
break;
}
return this.amplitudeCoefficient_;
};
/**
* Sets attack phase duration.
* @param {number} time Duration of the attack phase in seconds.
*/
doodle.moog.EnvelopeGenerator.prototype.setAttackTime = function(time) {
this.attackTime_ = time;
this.recomputePhaseSteps_();
};
/**
* Sets decay phase duration.
* @param {number} time Duration of the decay phase in seconds.
*/
doodle.moog.EnvelopeGenerator.prototype.setDecayTime = function(time) {
this.decayTime_ = time;
this.recomputePhaseSteps_();
};
/**
* Sets the sustain level.
* @param {number} level The sustain level, a number in the range [0, 1].
*/
doodle.moog.EnvelopeGenerator.prototype.setSustainLevel = function(level) {
this.sustainLevel_ = level;
this.recomputePhaseSteps_();
};
/**
* Updates phase step variables to reflect current EnvelopeGenerator state.
* @private
*/
doodle.moog.EnvelopeGenerator.prototype.recomputePhaseSteps_ = function() {
if (this.attackTime_ <= 0) {
this.attackStep_ = 1;
} else {
this.attackStep_ = this.SAMPLE_INTERVAL_ / this.attackTime_;
}
if (this.decayTime_ <= 0) {
this.decayStep_ = 1;
this.releaseStep_ = 1;
} else {
this.decayStep_ =
(1 - this.sustainLevel_) * this.SAMPLE_INTERVAL_ / this.decayTime_;
this.releaseStep_ =
this.sustainLevel_ * this.SAMPLE_INTERVAL_ / this.decayTime_;
}
};
|
010pepe010-moog
|
envelope_generator.js
|
JavaScript
|
asf20
| 7,743
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Interface for compound Web Audio audio nodes.
*/
goog.provide('doodle.moog.CompoundAudioNode');
/**
* Connection interface for compound Web Audio nodes.
* @interface
*/
doodle.moog.CompoundAudioNode = function() {};
/**
* Gets the source node for this compound node.
* @return {!AudioNode} The input/source node for this compound node.
*/
doodle.moog.CompoundAudioNode.prototype.getSourceNode = function() {};
/**
* Connects this compound node to a destination audio node.
* @param {!AudioNode} destination The destination to connect this node to.
*/
doodle.moog.CompoundAudioNode.prototype.connect = function(destination) {};
/**
* Disconnects this compound node from any destination audio node.
*/
doodle.moog.CompoundAudioNode.prototype.disconnect = function() {
};
|
010pepe010-moog
|
compound_audio_node.js
|
JavaScript
|
asf20
| 1,421
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A moog-like audio synthesizer built on top of the HTML5 Web
* Audio API.
*/
goog.provide('doodle.moog.SynthesizerInterface');
/**
* A Moog-like synthesizer built on top of the HTML5 Web Audio API.
* @interface
*/
doodle.moog.SynthesizerInterface = function() {};
/**
* Signals that a key on the synthesizer has been pressed.
* @param {number} note Chromatic index of the note to be played relative to
* the beginning of the keyboard.
*/
doodle.moog.SynthesizerInterface.prototype.setKeyDown = function(note) {};
/**
* Binds a callback to a key down event.
* @param {function(number)} callback The function called when a key is pressed.
*/
doodle.moog.SynthesizerInterface.prototype.setKeyDownCallback =
function(callback) {};
/**
* Signals that a key on the synthesizer has been released. Since the
* synthesizer is monophonic, no note parameter is necessary.
*/
doodle.moog.SynthesizerInterface.prototype.setKeyUp = function() {};
/**
* Increases/decreases the output gain.
* @param {number} volume The output volume level. A number in the range
* [0..1].
*/
doodle.moog.SynthesizerInterface.prototype.setVolume = function(volume) {};
/**
* Proxy to the synthesizer's low-pass filter setCutoffFrequency.
* @param {number} cutoffFrequency The cutoff frequency above which the
* frequencies are attenuated.
*/
doodle.moog.SynthesizerInterface.prototype.setLpCutoffFrequency =
function(cutoffFrequency) {};
/**
* Proxy to the synthesizer's low-pass filter setContour.
* @param {number} contour Amount of contour to apply to the filter envelope.
*/
doodle.moog.SynthesizerInterface.prototype.setLpContour =
function(contour) {};
/**
* Proxy to the synthesizer's low-pass filter setContourAttackTime.
* @param {number} time Duration of the attack phase in seconds.
*/
doodle.moog.SynthesizerInterface.prototype.setLpContourAttackTime =
function(time) {};
/**
* Proxy to the synthesizer's low-pass filter setContourDecayTime.
* @param {number} time Duration of the decay phase in seconds.
*/
doodle.moog.SynthesizerInterface.prototype.setLpContourDecayTime =
function(time) {};
/**
* Proxy to the synthesizer's low-pass filter setContourSustainLevel.
* @param {number} level The sustain level, a number in the range [0, 1].
*/
doodle.moog.SynthesizerInterface.prototype.setLpContourSustainLevel =
function(level) {};
|
010pepe010-moog
|
synthesizer_interface.js
|
JavaScript
|
asf20
| 3,037
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Voltage controlled oscillator emulators.
*/
goog.provide('doodle.moog.Oscillator');
goog.require('doodle.moog.EnvelopeGenerator');
goog.require('doodle.moog.OscillatorInterface');
/**
* A voltage controlled oscillator emulator built on the HTML5 Audio API. This
* is the root source of all sound in the Moog doodle.
*
* @param {!AudioContext} audioContext Audio context to which this oscillator
* will be bound.
* @param {number} volume Initial volume level [0..1].
* @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm Initial wave
* form.
* @param {!doodle.moog.OscillatorInterface.Range} range Initial pitch range.
* @param {number} pitchBend Initial pitch bend [-1..1].
* @param {boolean} isAcceptingKeyboardPitch Whether keyboard control is on.
* @param {boolean} isFrequencyModulationOn Whether this oscillator should
* modulate its frequency using the modulator control signal.
* @param {boolean} isModulator Whether this modulator should act as a modulator
* control signal in addition to an audio signal.
* @param {number} modulatorLevel If a modulator, how strong the modulator
* control signal should be [0..1].
* @param {boolean} isGlideOn Whether glide is on.
* @param {number} glideTime Glide time in seconds.
* @param {number} attackTime Initial attack time in seconds.
* @param {number} decayTime Initial decay time in seconds.
* @param {number} sustainLevel Initial sustain level [0..1].
* @constructor
* @implements {doodle.moog.OscillatorInterface}
*/
doodle.moog.Oscillator = function(
audioContext, volume, waveForm, range, pitchBend, isAcceptingKeyboardPitch,
isFrequencyModulationOn, isModulator, modulatorLevel, isGlideOn, glideTime,
attackTime, decayTime, sustainLevel) {
/**
* How many seconds pass with each sample.
* @type {number}
* @private
* @const
*/
this.SAMPLE_INTERVAL_ = 1 / audioContext.sampleRate;
/**
* How many seconds we have advanced in the current cycle.
* @type {number}
* @private
*/
this.phase_ = 0.0;
/**
* The amount of oscillator signal which is fed into the mixer. Mapped onto
* the range [0.0, 1.0] where 0 means muted and 1.0 means full loudness.
* @type {number}
* @private
*/
this.volume_ = volume;
/**
* Shape of the wave this oscillator generates.
* @type {!doodle.moog.OscillatorInterface.WaveForm}
* @private
*/
this.waveForm_ = waveForm;
/**
* Octave/range in which the oscillator functions.
* @type {!doodle.moog.OscillatorInterface.Range}
* @private
*/
this.range_ = range;
/**
* Pitch bend to apply on top of the base frequency on the range [-1.0, 1.0].
* If isAcceptingKeyboardPitch_ is true, -1/1 are a major 6th down/up; 0 is no
* pitch bend. If isAcceptingKeyboardPitch_ is false, -1/1 are 3 octaves
* down/up; 0 is still no pitch bend.
* @type {number}
* @private
*/
this.pitchBend_ = pitchBend;
/**
* Whether the oscillator pitch is controlled by keyboard signals. If true,
* the pitch follows the keyboard as one would expect on a piano-like
* instrument. If false, pressing any key on the keyboard will result in the
* same pitch (as set by range_ and pitchBend_).
* @type {boolean}
* @private
*/
this.isAcceptingKeyboardPitch_ = isAcceptingKeyboardPitch;
/**
* Whether this oscillator should modulate its frequency using the modulator
* control signal.
* @type {boolean}
* @private
*/
this.isFrequencyModulationOn_ = isFrequencyModulationOn;
/**
* Whether this modulator should act as a modulator control signal in addition
* to an audio signal.
* @type {boolean}
* @const
* @private
*/
this.IS_MODULATOR_ = isModulator;
/**
* If this oscillator is also a modulator, how strong the modulator control
* signal should be [0..1]. 0 fully attenuates the control signal; 1 fully
* applies it.
* @type {number}
* @private
*/
this.modulatorLevel_ = modulatorLevel;
/**
* If this oscillator is also a modulator, a buffer for storing modulator
* control signal samples. Null iff this oscillator does not act as a
* modulator.
* @type {Float32Array}
*/
this.modulatorSignal = null;
/**
* Whether glide (portamento sliding between notes) is enabled.
* @type {boolean}
* @private
*/
this.isGlideOn_ = isGlideOn;
/**
* Glide duration in seconds.
* @type {number}
* @private
*/
this.glideDuration_ = glideTime;
/**
* How much to advanced the frequency per sample while gliding. Null until
* the first tone is played.
* @type {?number}
* @private
*/
this.glideDelta_ = null;
/**
* Current glide pitch. Null until the first tone is played.
* @type {?number}
* @private
*/
this.currentGlidePitch_ = null;
/**
* Target glide pitch. Null until the first tone is played.
* @type {?number}
* @private
*/
this.targetGlidePitch_ = null;
/**
* Chromatic index of the note to be played relative to the beginning of the
* keyboard.
* @type {number}
* @private
*/
this.activeNote_ = 0;
/**
* Envelope generator that will shape the dynamics of this oscillator.
* @type {!doodle.moog.EnvelopeGenerator}
*/
this.envelopeGenerator =
new doodle.moog.EnvelopeGenerator(
this.SAMPLE_INTERVAL_, attackTime, decayTime, sustainLevel);
};
/**
* The base frequency (in hertz) from which other notes' frequencies are
* calculated. A low 'A'.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.BASE_FREQUENCY_ = 55;
/**
* Frequency ratio of major sixth musical interval.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_ = 5 / 3;
/**
* Frequency ratio of a three octave musical interval.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_ = 8;
/**
* The chromatic distance between keyboard notes (as passed to
* getInstantaneousFrequency_) and low A.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.NOTE_OFFSET_ = -4;
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setVolume = function(volume) {
this.volume_ = volume;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setWaveForm = function(waveForm) {
this.waveForm_ = waveForm;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setPitchBend = function(pitchBend) {
this.pitchBend_ = pitchBend;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setRange = function(range) {
this.range_ = range;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOnKeyboardPitchControl = function() {
this.isAcceptingKeyboardPitch_ = true;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOffKeyboardPitchControl = function() {
this.isAcceptingKeyboardPitch_ = false;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOnFrequencyModulation = function() {
this.isFrequencyModulationOn_ = true;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOffFrequencyModulation = function() {
this.isFrequencyModulationOn_ = false;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setModulatorLevel = function(modulatorLevel) {
this.modulatorLevel_ = modulatorLevel;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOnGlide = function() {
this.isGlideOn_ = true;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOffGlide = function() {
this.isGlideOn_ = false;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setGlideDuration = function(time) {
this.glideDuration_ = time;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setActiveNote = function(note) {
this.activeNote_ = note;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setEnvelopeGeneratorAttackTime =
function(attackTime) {
this.envelopeGenerator.setAttackTime(attackTime);
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setEnvelopeGeneratorDecayTime =
function(decayTime) {
this.envelopeGenerator.setDecayTime(decayTime);
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setEnvelopeGeneratorSustainLevel =
function(sustainLevel) {
this.envelopeGenerator.setSustainLevel(sustainLevel);
};
/**
* Gets the instantaneous frequency that this oscillator ought to be generating.
* @param {number} note Chromatic index of the note to be played relative to
* the beginning of the keyboard.
* @return {number} The instantaneous frequency.
* @private
*/
doodle.moog.Oscillator.prototype.getInstantaneousFrequency_ = function(note) {
if (!this.isAcceptingKeyboardPitch_) {
note = 0;
}
return doodle.moog.Oscillator.BASE_FREQUENCY_ *
this.range_ *
Math.pow(2, (note + doodle.moog.Oscillator.NOTE_OFFSET_) / 12);
};
/**
* Gets the pitch bend that should be applied to this oscillator.
* @return {number} The frequency ratio that should be applied to the base
* pitch.
* @private
*/
doodle.moog.Oscillator.prototype.getPitchBend_ = function() {
var pitchBendScale = doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_;
if (!this.isAcceptingKeyboardPitch_) {
pitchBendScale = doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_;
}
var normalizedPitchBend =
Math.abs(this.pitchBend_ * (pitchBendScale - 1)) + 1;
return this.pitchBend_ >= 0 ? normalizedPitchBend : 1 / normalizedPitchBend;
};
/**
* Gets the frequency this oscillator ought to generate after undergoing
* optional glide.
* @param {number} target The target frequency to move towards.
* @return {number} The frequency this oscillator should generate with glide.
* @private
*/
doodle.moog.Oscillator.prototype.getGlideFrequency_ = function(target) {
if (!this.isGlideOn_ ||
this.currentGlidePitch_ === null ||
this.glideDuration_ <= 0 ||
Math.abs(this.currentGlidePitch_ - target) <=
Math.abs(this.glideDelta_)) {
this.currentGlidePitch_ = this.targetGlidePitch_ = target;
return target;
}
if (this.targetGlidePitch_ != target) {
var glideDurationInSamples = this.glideDuration_ / this.SAMPLE_INTERVAL_;
this.glideDelta_ =
(target - this.currentGlidePitch_) / glideDurationInSamples;
this.targetGlidePitch_ = target;
}
this.currentGlidePitch_ += this.glideDelta_;
return this.currentGlidePitch_;
};
/**
* Gets the frequency this oscillator ought to generate after undergoing
* optional frequency modulation.
* @param {number} baseFrequency The base frequency to modulate.
* @param {Float32Array} modulatorSignal Modulator signal buffer to apply to
* this oscillator. If null, no modulation should be applied.
* @param {number} index Sample index of the modulation signal to apply.
* @return {number} The frequency this oscillator should generate with
* modulation.
* @private
*/
doodle.moog.Oscillator.prototype.getModulationFrequency_ = function(
baseFrequency, modulatorSignal, index) {
if (!modulatorSignal || !this.isFrequencyModulationOn_) {
return baseFrequency;
}
// Linearly project modulation level [0..1] onto [0.5..2] (down/up an octave).
// TODO: Re-evaluate this maximum frequency modulation range based on real
// Moog behavior.
return (modulatorSignal[index] * 0.75 + 1.25) * baseFrequency;
};
/**
* Advances the oscillator's phase of play. This helper function must be called
* exactly once per sample.
* @param {number} frequency The frequency being played.
* @return {number} Progress made in the current cycle, projected on the range
* [0, 1].
* @private
*/
doodle.moog.Oscillator.prototype.advancedPhase_ = function(frequency) {
var cycleLengthInSeconds = 2 / frequency;
if (this.phase_ > cycleLengthInSeconds) {
this.phase_ -= cycleLengthInSeconds;
}
var progressInCycle = this.phase_ * frequency / 2;
this.phase_ += this.SAMPLE_INTERVAL_;
return progressInCycle;
};
/**
* Fills the passed audio buffer with the tone represented by this oscillator.
* @param {!AudioProcessingEvent} e The audio process event object.
* @param {Float32Array} modulatorSignal Modulator signal buffer to apply to
* this oscillator. If null, no modulation will be applied.
* @param {!doodle.moog.OscillatorInterface.FillMode} fillMode How the
* oscillator should fill the passed audio buffer.
* @param {number=} opt_mixDivisor Iff using FillMode.MIX, how much to mix down
* the buffer. This should usually be the number of oscillators that have
* added data to the buffer.
*/
doodle.moog.Oscillator.prototype.fillAudioBuffer = function(
e, modulatorSignal, fillMode, opt_mixDivisor) {
var buffer = e.outputBuffer;
var left = buffer.getChannelData(1);
var right = buffer.getChannelData(0);
if (this.IS_MODULATOR_ && !this.modulatorSignal) {
this.modulatorSignal = new Float32Array(buffer.length);
}
var targetFrequency = this.getInstantaneousFrequency_(this.activeNote_);
var pitchBend = this.getPitchBend_();
var frequency = targetFrequency * pitchBend;
var audioLevel, envelopeCoefficient, level, on, progressInCycle, ramp;
for (var i = 0; i < buffer.length; ++i) {
envelopeCoefficient =
this.envelopeGenerator.getNextAmplitudeCoefficient();
progressInCycle = this.advancedPhase_(
pitchBend *
this.getModulationFrequency_(
this.getGlideFrequency_(targetFrequency), modulatorSignal, i));
switch (this.waveForm_) {
case doodle.moog.OscillatorInterface.WaveForm.TRIANGLE:
level = 4 * ((progressInCycle > 0.5 ?
1 - progressInCycle : progressInCycle) - .25);
break;
case doodle.moog.OscillatorInterface.WaveForm.SAWANGLE:
ramp = progressInCycle < 0.5;
level = ramp ? (4 * progressInCycle - 1) : (-2 * progressInCycle + 1);
break;
case doodle.moog.OscillatorInterface.WaveForm.RAMP:
level = 2 * (progressInCycle - 0.5);
break;
case doodle.moog.OscillatorInterface.WaveForm.REVERSE_RAMP:
level = -2 * (progressInCycle - 0.5);
break;
case doodle.moog.OscillatorInterface.WaveForm.SQUARE:
level = progressInCycle < 0.5 ? 1 : -1;
break;
case doodle.moog.OscillatorInterface.WaveForm.FAT_PULSE:
level = progressInCycle < 1 / 3 ? 1 : -1;
break;
case doodle.moog.OscillatorInterface.WaveForm.PULSE:
level = progressInCycle < 0.25 ? 1 : -1;
break;
}
if (this.IS_MODULATOR_) {
this.modulatorSignal[i] = level * this.modulatorLevel_;
}
audioLevel = level * this.volume_ * envelopeCoefficient;
if (fillMode == doodle.moog.OscillatorInterface.FillMode.CLOBBER) {
right[i] = audioLevel;
} else if (fillMode == doodle.moog.OscillatorInterface.FillMode.ADD) {
right[i] = right[i] + audioLevel;
} else { // Otherwise FillMode.MIX.
right[i] = (right[i] + audioLevel) / opt_mixDivisor;
// In older versions of Chrome, Web Audio API always created two
// channels even if you have requested monaural sound. However, this
// is not the case in the newer (dev/canary) versions. This should
// cover both.
if (left) {
left[i] = right[i];
}
}
}
};
|
010pepe010-moog
|
oscillator.js
|
JavaScript
|
asf20
| 15,905
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a wide band pass filter to protect headphones and
* speakers from really low and high frequencies.
*/
goog.provide('doodle.moog.WideBandPassFilter');
goog.require('doodle.moog.CompoundAudioNode');
/**
* A wide band pass filter designed to filter out low and high frequencies that
* might damage poorly made speakers connected to poorly made sound cards.
* @param {!AudioContext} audioContext Audio context to which this oscillator
* will be bound.
* @param {number} lowCutoffFrequency The cutoff frequency below which sound is
* attenuated.
* @param {number} highCutoffFrequency The cutoff frequency above which sound is
* attenuated.
* @constructor
* @implements {doodle.moog.CompoundAudioNode}
*/
doodle.moog.WideBandPassFilter = function(
audioContext, lowCutoffFrequency, highCutoffFrequency) {
/**
* The low pass filter Web Audio node.
* @type {!BiquadFilterNode}
* @private
*/
this.lowPassFilterNode_ = audioContext.createBiquadFilter();
this.lowPassFilterNode_.type =
doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_;
this.lowPassFilterNode_.frequency.value = highCutoffFrequency;
/**
* The high pass filter Web Audio node.
* @type {!BiquadFilterNode}
* @private
*/
this.highPassFilterNode_ = audioContext.createBiquadFilter();
this.highPassFilterNode_.type =
doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_;
this.highPassFilterNode_.frequency.value = lowCutoffFrequency;
this.lowPassFilterNode_.connect(this.highPassFilterNode_);
};
/**
* Biquad Filter type ID for a low pass filter (from the Web Audio spec).
* @type {number}
* @const
* @private
*/
doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0;
/**
* Biquad Filter type ID for a low pass filter (from the Web Audio spec).
* @type {number}
* @const
* @private
*/
doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_ = 1;
/** @inheritDoc */
doodle.moog.WideBandPassFilter.prototype.getSourceNode = function() {
return this.lowPassFilterNode_;
};
/** @inheritDoc */
doodle.moog.WideBandPassFilter.prototype.connect = function(destination) {
this.highPassFilterNode_.connect(destination);
};
/** @inheritDoc */
doodle.moog.WideBandPassFilter.prototype.disconnect = function() {
this.highPassFilterNode_.disconnect();
};
|
010pepe010-moog
|
wide_band_pass_filter.js
|
JavaScript
|
asf20
| 2,965
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Master mixer interface for all doodle Web Audio sources.
*/
goog.provide('doodle.moog.MasterMixerInterface');
/**
* Master mixer for the multiple virtual synthesizers that may play back
* simultaneously via the Sequencer.
* @interface
*/
doodle.moog.MasterMixerInterface = function() {};
/**
* Turns on the mixer.
*/
doodle.moog.MasterMixerInterface.prototype.turnOn = function() {};
/**
* Turns off the mixer.
*/
doodle.moog.MasterMixerInterface.prototype.turnOff = function() {};
|
010pepe010-moog
|
master_mixer_interface.js
|
JavaScript
|
asf20
| 1,129
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Main module for the Dr. Robert Moog Synthesizer doodle.
*/
goog.provide('doodle.moog.Moog');
goog.require('doodle.moog.LowPassFilter');
goog.require('doodle.moog.MasterMixer');
goog.require('doodle.moog.Oscillator');
goog.require('doodle.moog.OscillatorInterface');
goog.require('doodle.moog.Synthesizer');
goog.require('doodle.moog.WideBandPassFilter');
goog.require('goog.Disposable');
/**
* The Moog doodle manager.
* @constructor
* @extends {goog.Disposable}
*/
doodle.moog.Moog = function() {
goog.base(this);
/**
* The set of available synthesizers.
* @type {!Array.<!doodle.moog.SynthesizerInterface>}
* @private
*/
this.synthesizers_ = [];
/**
* A reference to a master mixer instance.
* @type {!doodle.moog.MasterMixerInterface}
* @private
*/
this.masterMixer_;
/**
* @private
*/
this.isWebAudioEnabled_ = typeof webkitAudioContext === 'function';
if (this.isWebAudioEnabled_) {
this.initializeWebAudio_();
}
};
goog.inherits(doodle.moog.Moog, goog.Disposable);
/** @inheritDoc */
doodle.moog.Moog.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.turnOffAudio();
};
/**
* Initializes the Moog doodle on WebAudio-compatible browsers.
* @private
*/
doodle.moog.Moog.prototype.initializeWebAudio_ = function() {
try {
// Audio context creation can throw an error if the user is missing sound
// drivers, etc.
var audioContext = new webkitAudioContext();
} catch(e7) {
// Abort the initialization sequence like we do with flash.
return;
}
var oscillators = [
new doodle.moog.Oscillator(
audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE,
doodle.moog.OscillatorInterface.Range.R16, 0, true, false, false, 0,
true, 0.05, 0, 0.4, 1),
new doodle.moog.Oscillator(
audioContext, 0.82, doodle.moog.OscillatorInterface.WaveForm.SQUARE,
doodle.moog.OscillatorInterface.Range.R4, 0, true, false, false, 0,
true, 0.05, 0, 0.4, 1),
new doodle.moog.Oscillator(
audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE,
doodle.moog.OscillatorInterface.Range.R32, 0, true, false, true, 0.6,
true, 0.05, 0, 0.4, 1)
];
var lowPassFilter = new doodle.moog.LowPassFilter(
audioContext, 2100, 7, 0, .8, 0);
this.synthesizers_.push(new doodle.moog.Synthesizer(
audioContext, oscillators, lowPassFilter, 0.82));
var wideBandPassFilter = new doodle.moog.WideBandPassFilter(
audioContext, 20, 20000);
this.masterMixer_ = new doodle.moog.MasterMixer(
audioContext, this.synthesizers_, wideBandPassFilter);
};
/**
* Turns on the audio pipeline.
*/
doodle.moog.Moog.prototype.turnOnAudio = function() {
if (this.masterMixer_) {
this.masterMixer_.turnOn();
}
};
/**
* Turns off the audio pipeline.
*/
doodle.moog.Moog.prototype.turnOffAudio = function() {
if (this.masterMixer_) {
this.masterMixer_.turnOff();
}
};
|
010pepe010-moog
|
moog.js
|
JavaScript
|
asf20
| 3,633
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Master mixer for all doodle Web Audio sources.
*/
goog.provide('doodle.moog.MasterMixer');
goog.require('doodle.moog.MasterMixerInterface');
/**
* Master mixer for the multiple virtual synthesizers that may play back
* simultaneously via the Sequencer.
* @param {!AudioContext} audioContext Audio context in which this mixer will
* operate.
* @param {!Array.<!doodle.moog.SynthesizerInterface>} synthesizers The
* synthesizers that feed into this mixer.
* @param {!doodle.moog.WideBandPassFilter} wideBandPassFilter The wide band
* pass filter used within this mixer.
* @constructor
* @implements {doodle.moog.MasterMixerInterface}
*/
doodle.moog.MasterMixer = function(
audioContext, synthesizers, wideBandPassFilter) {
/**
* The audio context in which this mixer operates.
* @type {!AudioContext}
* @private
*/
this.audioContext_ = audioContext;
/**
* The synthesizers this mixer mixes.
* @type {!Array.<!doodle.moog.Synthesizer>}
* @private
*/
this.synthesizers_ = synthesizers;
/**
* Filter used to cut out really low/high frequencies.
* @type {!doodle.moog.WideBandPassFilter}
* @private
*/
this.wideBandPassFilter_ = wideBandPassFilter;
for (var i = 0; i < synthesizers.length; i++) {
synthesizers[i].connect(wideBandPassFilter.getSourceNode());
}
};
/** @inheritDoc */
doodle.moog.MasterMixer.prototype.turnOn = function() {
window.setTimeout(goog.bind(function() {
// NOTE: The audio pipeline is connected in a setTimeout to avoid a Chrome
// bug in which the audio will occasionally fail to initialize/play.
this.wideBandPassFilter_.connect(this.audioContext_.destination);
}, this), 0);
};
/** @inheritDoc */
doodle.moog.MasterMixer.prototype.turnOff = function() {
this.wideBandPassFilter_.disconnect();
};
|
010pepe010-moog
|
master_mixer.js
|
JavaScript
|
asf20
| 2,462
|
#include <iostream>
using namespace std;
int main()
{
int height;
float eyesight;
height = 175;
eyesight = 0.8f;
bool ok;
ok = height >= 160 && height <=180 &&
eyesight >= 1.0f && eyesight <= 2.0f;
cout << boolalpha;
cout << ok << endl;
return 0;
}
|
103956-kirak-cpp
|
helloWorld/helloWorld/HelloWorld.cpp
|
C++
|
asf20
| 285
|
int main()
{
int a = 100;
int b = 200;
int c = 300;
return 0;
}
|
103956-kirak-cpp
|
test/test/test.cpp
|
C++
|
asf20
| 81
|
#include<iostream>
using namespace std;
void main()
{
int a[10], i;
for(i=0; i<10; i++)
a[i]=i+1;
for(i=0; i<10; i++)
cout << a[i] << " ";
cout <<"\n";
}
|
103956-kirak-cpp
|
CLASS6_1/CLASS6_1/CLASS6.cpp
|
C++
|
asf20
| 210
|
if False: # set to True to insert test data
store(store.product.id > 0).delete()
store(store.category.id > 0).delete()
if len(store(store.product.id > 0).select()) == 0:
fantasy_id = store.category.insert(name='Fantasy', description='Fantasy books', small_image='testdata/hp1.jpg')
hp1 = store.product.insert(name="Harry Potter and the Sorcerer's Stone", category=fantasy_id, price=7.91, small_image='testdata/hp1.jpg')
hp2 = store.product.insert(name="Harry Potter and the Chamber of Secrets", category=fantasy_id, price=8.91, small_image='testdata/hp2.jpg')
hp3 = store.product.insert(name="Harry Potter and the Prisoner of Azkaban", category=fantasy_id, price=8.91, small_image='testdata/hp3.jpg')
hp4 = store.product.insert(name="Harry Potter and the Goblet of Fire", category=fantasy_id, price=9.91, small_image='testdata/hp4.jpg')
hp5 = store.product.insert(name="Harry Potter and the Order of the Phoenix", category=fantasy_id, price=9.91, small_image='testdata/hp5.jpg')
hp6 = store.product.insert(name="Harry Potter and the Half-Blood Prince", category=fantasy_id, price=9.91, small_image='testdata/hp6.jpg')
store.option.insert(product=hp1, description='Bookmark', price=1.5)
store.option.insert(product=hp1, description='Wizard hat', price=12)
for p2 in (hp2, hp3, hp4, hp5, hp6):
store.cross_sell.insert(p1=hp1, p2=p2)
hp1_hard = store.product.insert(name="Harry Potter and the Sorcerer's Stone [hardcover]", category=fantasy_id, price=15.91, small_image='testdata/hp1.jpg')
store.up_sell.insert(product=hp1, better=hp1_hard)
|
0707tim-web2pestore
|
models/testdata.py
|
Python
|
gpl2
| 1,693
|
UNDEFINED = -1
if request.env.web2py_runtime_gae: # if running on Google App Engine
store = DAL('gae') # connect to Google BigTable
session.connect(request, response, db=store) # and store sessions and tickets there
else:
store = DAL("sqlite://store.db")
store.define_table('category',
Field('name'),
Field('description', 'text'),
Field('small_image', 'upload'),
)
store.define_table('product',
Field('name'),
Field('category', store.category),
Field('description', 'text', default=''),
Field('small_image', 'upload'),
Field('large_image', 'upload', default=''),
Field('quantity_in_stock', 'integer', default=UNDEFINED), # if UNDEFINED, don't show
Field('max_quantity', 'integer', default=0), # maximum quantity that can be purchased in an order. If 0, no limit. If UNDEFINED, don't show.
Field('price', 'double', default=1.0),
Field('old_price', 'double', default=0.0),
Field('weight_in_pounds', 'double', default=1),
Field('tax_rate_in_your_state', 'double', default=10.0),
Field('tax_rate_outside_your_state', 'double', default=0.0),
Field('featured', 'boolean', default=False),
Field('allow_rating', 'boolean', default=False),
Field('rating', 'integer', default='0'),
Field('viewed', 'integer', default='0'),
Field('clicked', 'integer', default='0'))
# each product can have optional addons
store.define_table('option',
Field('product', store.product),
Field('description'),
Field('price', 'double', default=1.0),
)
# support for merchandising
# for p1 show p2, and for p2 show p1
store.define_table('cross_sell',
Field('p1', store.product),
Field('p2', store.product),
)
# for product, show better, but not the reverse
store.define_table('up_sell',
Field('product', store.product),
Field('better', store.product),
)
store.define_table('comment',
Field('product', store.product),
Field('author'),
Field('email'),
Field('body', 'text'),
Field('rate', 'integer')
)
store.define_table('info',
Field('google_merchant_id', default='[google checkout id]', length=256),
Field('name', default='[store name]'),
Field('headline', default='[store headline]'),
Field('address', default='[store address]'),
Field('city', default='[store city]'),
Field('state', default='[store state]'),
Field('zip_code', default='[store zip]'),
Field('phone', default='[store phone number]'),
Field('fax', default='[store fax number]'),
Field('email', requires=IS_EMAIL(), default='yourname@yourdomain.com'),
Field('description', 'text', default='[about your store]'),
Field('why_buy', 'text', default='[why buy at your store]'),
Field('return_policy', 'text', default='[what is your return policy]'),
Field('logo', 'upload', default=''),
Field('color_background', length=10, default='white'),
Field('color_foreground', length=10, default='black'),
Field('color_header', length=10, default='#F6F6F6'),
Field('color_link', length=10, default='#385ea2'),
Field('font_family', length=32, default='arial, helvetica'),
Field('ship_usps_express_mail', 'boolean', default=True),
Field('ship_usps_express_mail_fc', 'double', default=0),
Field('ship_usps_express_mail_vc', 'double', default=0),
Field('ship_usps_express_mail_bc', 'double', default=0),
Field('ship_usps_priority_mail', 'boolean', default=True),
Field('ship_usps_priority_mail_fc', 'double', default=0),
Field('ship_usps_priority_mail_vc', 'double', default=0),
Field('ship_usps_priority_mail_bc', 'double', default=0),
Field('ship_ups_next_day_air', 'boolean', default=True),
Field('ship_ups_next_day_air_fc', 'double', default=0),
Field('ship_ups_next_day_air_vc', 'double', default=0),
Field('ship_ups_next_day_air_bc', 'double', default=0),
Field('ship_ups_second_day_air', 'boolean', default=True),
Field('ship_ups_second_day_air_fc', 'double', default=0),
Field('ship_ups_second_day_air_vc', 'double', default=0),
Field('ship_ups_second_day_air_bc', 'double', default=0),
Field('ship_ups_ground', 'boolean', default=True),
Field('ship_ups_ground_fc', 'double', default=0),
Field('ship_ups_ground_vc', 'double', default=0),
Field('ship_ups_ground_bc', 'double', default=0),
Field('ship_fedex_priority_overnight', 'boolean', default=True),
Field('ship_fedex_priority_overnight_fc', 'double', default=0),
Field('ship_fedex_priority_overnight_vc', 'double', default=0),
Field('ship_fedex_priority_overnight_bc', 'double', default=0),
Field('ship_fedex_second_day', 'boolean', default=True),
Field('ship_fedex_second_day_fc', 'double', default=0),
Field('ship_fedex_second_day_vc', 'double', default=0),
Field('ship_fedex_second_day_bc', 'double', default=0),
Field('ship_fedex_ground', 'boolean', default=True),
Field('ship_fedex_ground_fc', 'double', default=0),
Field('ship_fedex_ground_vc', 'double', default=0),
Field('ship_fedex_ground_bc', 'double', default=0)
)
store.category.name.requires = IS_NOT_IN_DB(store, 'category.name')
store.product.name.requires = IS_NOT_IN_DB(store, 'product.name')
store.product.category.requires = IS_IN_DB(store, 'category.id', 'category.name')
store.product.name.requires = IS_NOT_EMPTY()
store.product.description.requires = IS_NOT_EMPTY()
store.product.quantity_in_stock.requires = IS_INT_IN_RANGE(0, 1000)
store.product.price.requires = IS_FLOAT_IN_RANGE(0, 10000)
store.product.rating.requires = IS_INT_IN_RANGE(-10000, 10000)
store.product.viewed.requires = IS_INT_IN_RANGE(0, 1000000)
store.product.clicked.requires = IS_INT_IN_RANGE(0, 1000000)
store.option.product.requires = IS_IN_DB(store, 'product.id', 'product.name')
store.cross_sell.p1.requires = IS_IN_DB(store, 'product.id', 'product.name')
store.cross_sell.p2.requires = IS_IN_DB(store, 'product.id', 'product.name')
store.up_sell.product.requires = IS_IN_DB(store, 'product.id', 'product.name')
store.up_sell.better.requires = IS_IN_DB(store, 'product.id', 'product.name')
store.comment.product.requires = IS_IN_DB(store, 'product.id', 'product.name')
store.comment.author.requires = IS_NOT_EMPTY()
store.comment.email.requires = IS_EMAIL()
store.comment.body.requires = IS_NOT_EMPTY()
store.comment.rate.requires = IS_IN_SET(range(5, 0, -1))
for field in store.info.fields:
if field[:-2] in ['fc', 'vc']:
store.info[field].requires = IS_FLOAT_IN_RANGE(0, 100)
if len(store(store.info.id > 0).select()) == 0:
store.info.insert(name='[store name]')
mystore = store(store.info.id > 0).select()[0]
|
0707tim-web2pestore
|
models/store.py
|
Python
|
gpl2
| 6,730
|
#
import re
# delimiter to use between words in URL
URL_DELIMITER = '-'
def pretty_url(id, name):
"""Create pretty URL from record name and ID
"""
return '%s%s%d' % (' '.join(re.sub('[^\w ]+', '', name).split()).replace(' ', URL_DELIMITER), URL_DELIMITER, id)
def pretty_id(url):
"""Extract id from pretty URL
"""
return int(url.rpartition(URL_DELIMITER)[-1])
def pretty_text(s):
"Make text pretty by capitalizing and using 'home' instead of 'default'"
return s.replace('default', 'home').replace('_', ' ').capitalize()
def title():
if response.title:
return response.title
elif request.function == 'index':
return pretty_text(request.controller)
else:
return pretty_text(request.function)
|
0707tim-web2pestore
|
models/globals.py
|
Python
|
gpl2
| 779
|
###########################################################
### make sure administrator is on localhost
############################################################
import os, socket, datetime,copy
import gluon.contenttype
import gluon.fileutils
### crytical --- make a copy of the environment
global_env=copy.copy(globals())
global_env['datetime']=datetime
http_host = request.env.http_host.split(':')[0]
remote_addr = request.env.remote_addr
try: hosts=(http_host, socket.gethostbyname(remote_addr))
except: hosts=(http_host,)
if remote_addr not in hosts:
pass #raise HTTP(400)
if not gluon.fileutils.check_credentials(request):
redirect('/admin')
response.view='appadmin.html'
response.menu=[[T('design'),False,URL('admin','default','design',
args=[request.application])],
[T('db'),False,URL(r=request,f='index')],
[T('state'),False,URL(r=request,f='state')]]
###########################################################
### auxiliary functions
############################################################
def get_databases(request):
dbs={}
for key,value in global_env.items():
cond=False
try: cond=isinstance(value,GQLDB)
except: cond=isinstance(value,SQLDB)
if cond: dbs[key]=value
return dbs
databases=get_databases(None)
def eval_in_global_env(text):
exec('_ret=%s'%text,{},global_env)
return global_env['_ret']
def get_database(request):
if request.args and request.args[0] in databases:
return eval_in_global_env(request.args[0])
else:
session.flash=T('invalid request')
redirect(URL(r=request,f='index'))
def get_table(request):
db=get_database(request)
if len(request.args)>1 and request.args[1] in db.tables:
return db,request.args[1]
else:
session.flash=T('invalid request')
redirect(URL(r=request,f='index'))
def get_query(request):
try:
return eval_in_global_env(request.vars.query)
except Exception:
return None
###########################################################
### list all databases and tables
############################################################
def index():
return dict(databases=databases)
###########################################################
### insert a new record
############################################################
def insert():
db,table=get_table(request)
form=SQLFORM(db[table])
if form.accepts(request.vars,session):
response.flash=T('new record inserted')
return dict(form=form)
###########################################################
### list all records in table and insert new record
############################################################
def download():
import os
db=get_database(request)
filename=request.args[1]
print filename
### for GAE only ###
table,field=filename.split('.')[:2]
if table in db.tables and field in db[table].fields:
uploadfield=db[table][field].uploadfield
if isinstance(uploadfield,str):
from gluon.contenttype import contenttype
response.headers['Content-Type']=contenttype(filename)
rows=db(db[table][field]==filename).select()
return rows[0][uploadfield]
### end for GAE ###
path=os.path.join(request.folder,'uploads/',filename)
return response.stream(open(path,'rb'))
def csv():
import gluon.contenttype
response.headers['Content-Type']=gluon.contenttype.contenttype('.csv')
query=get_query(request)
if not query: return None
response.headers['Content-disposition']="attachment; filename=%s_%s.csv"%\
tuple(request.vars.query.split('.')[:2])
return str(db(query).select())
def import_csv(table,file):
import csv
reader = csv.reader(file)
colnames=None
for line in reader:
if not colnames:
colnames=[x[x.find('.')+1:] for x in line]
c=[i for i in range(len(line)) if colnames[i]!='id']
else:
items=[(colnames[i],line[i]) for i in c]
table.insert(**dict(items))
def select():
import re
db=get_database(request)
dbname=request.args[0]
regex=re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)')
if request.vars.query:
match=regex.match(request.vars.query)
if match: request.vars.query='%s.%s.%s==%s' % (request.args[0],match.group('table'),match.group('field'),match.group('value'))
else:
request.vars.query=session.last_query
query=get_query(request)
if request.vars.start: start=int(request.vars.start)
else: start=0
nrows=0
stop=start+100
table=None
rows=[]
orderby=request.vars.orderby
if orderby:
orderby=dbname+'.'+orderby
if orderby==session.last_orderby:
if orderby[0]=='~': orderby=orderby[1:]
else: orderby='~'+orderby
session.last_orderby=orderby
session.last_query=request.vars.query
form=FORM(TABLE(TR('Query:','',INPUT(_style='width:400px',_name='query',_value=request.vars.query or '',requires=IS_NOT_EMPTY())),
TR('Update:',INPUT(_name='update_check',_type='checkbox',value=False),
INPUT(_style='width:400px',_name='update_fields',_value=request.vars.update_fields or '')),
TR('Delete:',INPUT(_name='delete_check',_class='delete',_type='checkbox',value=False),''),
TR('','',INPUT(_type='submit',_value='submit'))))
if request.vars.csvfile!=None:
try:
import_csv(db[request.vars.table],request.vars.csvfile.file)
response.flash=T('data uploaded')
except:
response.flash=T('unable to parse csv file')
if form.accepts(request.vars,formname=None):
regex=re.compile(request.args[0]+'\.(?P<table>\w+)\.id\>0')
match=regex.match(form.vars.query.strip())
if match: table=match.group('table')
try:
nrows=db(query).count()
if form.vars.update_check and form.vars.update_fields:
db(query).update(**eval_in_global_env('dict(%s)'%form.vars.update_fields))
response.flash=T('%s rows updated',nrows)
elif form.vars.delete_check:
db(query).delete()
response.flash=T('%s rows deleted',nrows)
nrows=db(query).count()
if orderby: rows=db(query).select(limitby=(start,stop), orderby=eval_in_global_env(orderby))
else: rows=db(query).select(limitby=(start,stop))
except:
rows,nrows=[],0
response.flash=T('Invalid Query')
return dict(form=form,table=table,start=start,stop=stop,nrows=nrows,rows=rows,query=request.vars.query)
###########################################################
### edit delete one record
############################################################
def update():
db,table=get_table(request)
try:
id=int(request.args[2])
record=db(db[table].id==id).select()[0]
except:
session.flash=T('record does not exist')
redirect(URL(r=request,f='select',args=request.args[:1],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2]))))
form=SQLFORM(db[table],record,deletable=True,
linkto=URL(r=request,f='select',args=request.args[:1]),
upload=URL(r=request,f='download',args=request.args[:1]))
if form.accepts(request.vars,session):
response.flash=T('done!')
redirect(URL(r=request,f='select',args=request.args[:1],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2]))))
return dict(form=form)
###########################################################
### get global variables
############################################################
def state(): return dict()
|
0707tim-web2pestore
|
controllers/appadmin.py
|
Python
|
gpl2
| 7,872
|
if not session.cart:
# instantiate new cart
session.cart, session.balance = [], 0
session.google_merchant_id = mystore.google_merchant_id
response.menu = [
['Store Front', request.function == 'index', URL(r=request, f='index')],
['About Us', request.function == 'aboutus', URL(r=request, f='aboutus')],
['Contact Us', request.function == 'contactus', URL(r=request, f='contactus')],
['Shopping Cart $%.2f' % float(session.balance), request.function == 'checkout', URL(r=request, f='checkout')]
]
def index():
categories = store().select(store.category.ALL, orderby=store.category.name)
featured = store(store.product.featured == True).select()
return dict(categories=categories,featured=featured)
def category():
if not request.args: redirect(URL(r=request, f='index'))
category_id = pretty_id(request.args[0])
if len(request.args) == 3:
# pagination
start, stop = int(request.args[1]), int(request.args[2])
else:
start, stop = 0, 20
categories = store().select(store.category.ALL, orderby=store.category.name)
category_name = None
for category in categories:
if category.id == category_id:
response.title = category_name = category.name
if not category_name: redirect(URL(r=request, f='index'))
if start == 0:
featured = store(store.product.featured == True)(store.product.category == category_id).select()
else:
featured = []
ids = [p.id for p in featured]
favourites = store(store.product.category == category_id).select(limitby=(start, stop))
favourites = [f for f in favourites if f.id not in ids]
return dict(category_name=category_name, categories=categories, featured=featured, favourites=favourites)
def product():
if not request.args: redirect(URL(r=request, f='index'))
product_id = pretty_id(request.args[0])
products = store(store.product.id == product_id).select()
if not products: redirect(URL(r=request, f='index'))
product = products[0]
response.title = product.name
product.update_record(viewed=product.viewed+1)
options = store(store.option.product == product.id).select()
product_form = FORM(
TABLE(
[TR(TD(INPUT(_name='option', _value=option.id, _type='checkbox', _onchange="update_price(this, %.2f)" % option.price), option.description), H3('$%.2f' % option.price)) for option in options],
TR(
'Price:',
H2('$%.2f' % float(product.price), _id='total_price')
),
BR(),
TH('Qty:', INPUT(_name='quantity', _class='integer', _value=1, _size=1)), INPUT(_type='submit', _value='Add to cart'),
)
)
if product_form.accepts(request.vars, session):
quantity = int(product_form.vars.quantity)
option_ids = product_form.vars.option
if not isinstance(option_ids, list):
option_ids = [option_ids] if option_ids else []
option_ids = [int(o) for o in option_ids]
product.update_record(clicked=product.clicked+1)
session.cart.append((product_id, quantity, option_ids))
redirect(URL(r=request, f='checkout'))
# post a comment about a product
comment_form = SQLFORM(store.comment, fields=['author', 'email', 'body', 'rate'])
comment_form.vars.product = product.id
if comment_form.accepts(request.vars, session):
nc = store(store.comment.product == product.id).count()
t = products[0].rating*nc + int(comment_form.vars.rate)
products[0].update_record(rating=t/(nc+1))
response.flash = 'comment posted'
if comment_form.errors: response.flash = 'invalid comment'
comments = store(store.comment.product == product.id).select()
better_ids = [row.better for row in store(store.up_sell.product == product.id).select(store.up_sell.better)]
related_ids = [row.p2 for row in store(store.cross_sell.p1 == product.id).select()] + [row.p1 for row in store(store.cross_sell.p2 == product.id).select()]
suggested = [store.product[id] for id in better_ids + related_ids] # XXXstore(store.product.id.belongs(better_ids + related_ids)).select()
return dict(product=product, comments=comments, options=options, suggested=suggested, product_form=product_form, comment_form=comment_form)
"""
{{ if product.old_price: }}
<b>was ${{= '%.2f' % float(product.old_price) }}</b>
{{ pass }}
</form>
"""
def remove_from_cart():
# remove product from cart
del session.cart[int(request.args[0])]
redirect(URL(r=request, f='checkout'))
def empty_cart():
# empty cart of all products
session.cart.clear()
session.balance = 0
redirect(URL(r=request, f='checkout'))
def checkout():
order = []
balance = 0
for product_id, qty, option_ids in session.cart:
products = store(store.product.id == product_id).select()
if products:
product = products[0]
options = [store.option[id] for id in option_ids]# XXX store(store.option.id.belongs(option_ids)).select() if option_ids else []
total_price = qty * (product.price + sum([option.price for option in options]))
order.append((product_id, qty, total_price, product, options))
balance += total_price
else:
# invalid product
pass
session.balance = balance # XXX is updating in time?
return dict(order=order, merchant_id=session.google_merchant_id)
def popup():
return dict()
def show():
response.session_id = None
import gluon.contenttype, os
filename = '/'.join(request.args)
response.headers['Content-Type'] = gluon.contenttype.contenttype(filename)
# XXX is this path going to be a problem on Windows?
return open(os.path.join(request.folder, 'uploads', filename), 'rb').read()
def aboutus(): return dict()
def contactus(): return dict()
|
0707tim-web2pestore
|
controllers/default.py
|
Python
|
gpl2
| 5,948
|
###########################################################
### make sure administrator is on localhost
############################################################
import os
from gluon.contenttype import contenttype
from gluon.fileutils import check_credentials, listdir
if not session.authorized and not request.function=='login':
redirect(URL(r=request,f='login'))
response.view='manage.html'
response.menu=[['manage',True,'/%s/manage/index' % (request.application)],
['logout',False,'/%s/manage/logout' % (request.application)],
['back to store',False,'/%s/default/index' % (request.application)]]
###########################################################
### list all tables in database
############################################################
def login():
response.view='manage/login.html'
from gluon.fileutils import check_credentials
if check_credentials(request,'admin'):
session.authorized=True
redirect(URL(r=request,f='index'))
return dict()
def logout():
session.authorized=False
redirect(URL(r=request,c='default',f='index'))
def index():
import types as _types
_dbs={}
for _key,_value in globals().items():
try:
if _value.__class__==SQLDB:
tables=_dbs[_key]=[]
for _tablename in _value.tables():
tables.append((_key,_tablename))
except: pass
return dict(dbs=_dbs)
###########################################################
### insert a new record
############################################################
def insert():
try:
dbname=request.args[0]
db=eval(dbname)
table=request.args[1]
form=SQLFORM(db[table])
except: redirect(URL(r=request,f='index'))
if form.accepts(request.vars,session):
response.flash='new record inserted'
redirect(URL(r=request,f='select',args=request.args))
elif len(request.vars):
response.flash='There are error in your submission form'
return dict(form=form)
###########################################################
### list all records in table and insert new record
############################################################
def download():
filename=request.args[0]
response.headers['Content-Type']=contenttype(filename)
return open(os.path.join(request.folder,'uploads/','%s' % filename),'rb').read()
def csv():
import gluon.contenttype, csv, cStringIO
response.headers['Content-Type']=gluon.contenttype.contenttype('.csv')
try:
dbname=request.vars.dbname
db=eval(dbname)
records=db(request.vars.query).select()
except: redirect(URL(r=request,f='index'))
s=cStringIO.StringIO()
writer = csv.writer(s)
writer.writerow(records.colnames)
c=range(len(records.colnames))
for i in range(len(records)):
writer.writerow([records.response[i][j] for j in c])
### FILL HERE
return s.getvalue()
def import_csv(table,file):
import csv
reader = csv.reader(file)
colnames=None
for line in reader:
if not colnames:
colnames=[x[x.find('.')+1:] for x in line]
c=[i for i in range(len(line)) if colnames[i]!='id']
else:
items=[(colnames[i],line[i]) for i in c]
table.insert(**dict(items))
def select():
try:
dbname=request.args[0]
db=eval(dbname)
if not request.vars.query:
table=request.args[1]
query='%s.id>0' % table
else: query=request.vars.query
except: redirect(URL(r=request,f='index'))
if request.vars.csvfile!=None:
try:
import_csv(db[table],request.vars.csvfile.file)
response.flash='data uploaded'
except: reponse.flash='unable to parse csv file'
if request.vars.delete_all and request.vars.delete_all_sure=='yes':
try:
db(query).delete()
response.flash='records deleted'
except: response.flash='invalid SQL FILTER'
elif request.vars.update_string:
try:
env=dict(db=db,query=query)
exec('db(query).update('+request.vars.update_string+')') in env
response.flash='records updated'
except: response.flash='invalid SQL FILTER or UPDATE STRING'
if request.vars.start: start=int(request.vars.start)
else: start=0
limitby=(start,start+100)
try:
records=db(query).select(limitby=limitby)
except:
response.flash='invalid SQL FILTER'
return dict(records='no records',nrecords=0,query=query,start=0)
linkto=URL(r=request,f='update/%s'% (dbname))
upload=URL(r=request,f='download')
return dict(start=start,query=query,\
nrecords=len(records),\
records=SQLTABLE(records,linkto,upload,_class='sortable'))
###########################################################
### edit delete one record
############################################################
def update():
try:
dbname=request.args[0]
db=eval(dbname)
table=request.args[1]
except: redirect(URL(r=request,f='index'))
try:
id=int(request.args[2])
record=db(db[table].id==id).select()[0]
except: redirect(URL(r=request,f='select/%s/%s'%(dbname,table)))
form=SQLFORM(db[table],record,deletable=True,
linkto=URL(r=request,f='select/'+dbname),
upload=URL(r=request,f='download/'))
if form.accepts(request.vars,session):
response.flash='done!'
redirect(URL(r=request,f='select/%s/%s'%(dbname,table)))
return dict(form=form)
def cleanup():
app=request.application
files=listdir('applications/%s/cache/' % app,'',0)
for file in files: os.unlink(file)
files=listdir('applications/%s/errors/' % app,'',0)
for file in files: os.unlink(file)
files=listdir('applications/%s/sessions/' % app,'',0)
for file in files: os.unlink(file)
session.flash="cache, errors and sessions cleaned"
redirect(URL(r=request,f='index'))
def setup():
response.view='manage/setup.html'
form=SQLFORM(store.info,mystore)
if form.accepts(request.vars,session):
response.flash='that was easy! now go vist your store.'
else:
response.flash='welcome to the store-in-a-stick setup'
return dict(form=form)
|
0707tim-web2pestore
|
controllers/manage.py
|
Python
|
gpl2
| 6,428
|
{{ def show(products, width=4, function='product'): }}
<table>
{{ for i, product in enumerate(products): }}
{{ if i == 0: }}
<tr>
{{ elif i % width == 0: }}
</tr>
<tr>
{{ pass }}
<td style="text-align: center">
<a href="{{= URL(r=request, f=function, args=pretty_url(product.id, product.name)) }}">
<img src="{{= URL(r=request, f='show', args=product.small_image) }}" height="100px"/>
<div>{{= product.name }}</div>
</a>
</td>
{{ pass }}
</tr>
</table>
{{ return }}
|
0707tim-web2pestore
|
views/catalog.html
|
HTML
|
gpl2
| 585
|
{{ extend 'layout.html' }}
<h2>Login to the Administrative Interface</h2><br/>
<form action="" method="post">
<table>
<tr><td>Administrator Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td></td><td><input type="submit" value="login"/></td></tr>
</table>
</form>
|
0707tim-web2pestore
|
views/manage/login.html
|
HTML
|
gpl2
| 299
|
{{ extend 'layout.html' }}
<h1>web2py Store Setup</h1>
<h2>Instructions</h2>
<ul>
<li>Register with <a href="http://checkout.google.com">Google Checkout</a></li>
<li>Google will assign you a "merchant id", insert it below</li>
<li>web2py/store comes with some example products in the database. Access the <a href="/{{=request.application}}/manage/index">application administrative interface</a> to create/edit/delete products and categories</li>
<li>Users can access the store <a href="/{{=request.application}}">here</a></li>
</ul>
<br/><br/>
<h2>Merchant ID</h2>
merchant id (as assigned by Google checkout):{{=form}}
<br/><br/>
<h2>Notes</h2>
<p>You can try web2py/store without a merchant_id, just type something in the field below. You can come back to <a href="/{{=request.application}}/default/setup">this page</a> later and change it.</p>
<p>Mind that, for you protection, web2py/store delegates to Google checkout the processing of your customers' shopping carts therefore web2py/store does not keep track of purchases and does not collect or store customers' credit card information. Google checkout will handle all that and will notify you, by email, when a purchase is completed.</p>
|
0707tim-web2pestore
|
views/manage/setup.html
|
HTML
|
gpl2
| 1,200
|
{{ extend 'layout.html' }}
{{ import cgi }}
<h1>Contact Us</h1>
<h2>Address</h2>
<p>{{= XML(cgi.escape(mystore.address).replace(', ','<br/>').replace('\n','</p><p>')) }}<br/>
{{= A('directions',_href='http://maps.google.com/maps?f=q&hl=en&geocode=&time=&date=&ttype=&q=%s' % cgi.escape(mystore.address)) }}</p>
<h2>Fax Number</h2>
<p>{{= mystore.fax }}</p>
<h2>Phone Number</h2>
<p>{{= mystore.phone }}</p>
<h2>Email</h2>
<p>{{= A(mystore.email, _href='mailto:%s' % mystore.email) }}</p>
|
0707tim-web2pestore
|
views/default/contactus.html
|
HTML
|
gpl2
| 497
|
{{ extend 'layout.html' }}
<h1>web2py Store Setup</h1>
<h2>Instructions</h2>
<ul>
<li>Register with <a href="http://checkout.google.com">Google Checkout</a></li>
<li>Google will assign you a "merchant id", insert it below</li>
<li>web2py/store comes with some example products in the database. Access the <a href="/{{= request.application }}/manage/index">application administrative interface</a> to create/edit/delete products and categories</li>
<li>Users can access the store <a href="/{{= request.application }}">here</a></li>
</ul>
<br/><br/>
<h2>Merchant ID</h2>
merchant id (as assigned by Google checkout):{{= form }}
<br/><br/>
<h2>Notes</h2>
<p>You can try web2py/store without a merchant_id, just type something in the field below. You can come back to <a href="/{{=request.application }}/default/setup">this page</a> later and change it.</p>
<p>Mind that, for you protection, web2py/store delegates to Google checkout the processing of your customers' shopping carts therefore web2py/store does not keep track of purchases and does not collect or store customers' credit card information. Google checkout will handle all that and will notify you, by email, when a purchase is completed.</p>
|
0707tim-web2pestore
|
views/default/setup.html
|
HTML
|
gpl2
| 1,224
|
{{ extend 'layout.html' }}
{{ include 'catalog.html' }}
<h1>Checkout</h1>
{{ if not order: }}
<h2>No products in your shopping cart</h2>
{{ else: }}
<h2>Products in your shopping cart</h2>
<table>
<tr>
<th>Product</th>
<th>Total</th>
</tr>
{{ for i, (product_id, qty, total_price, product, options) in enumerate(order): }}
<tr>
<td>
{{= qty }} x {{= A(product.name, _href=URL(r=request, f='product', args=pretty_url(product.id, product.name))) }}
<table>
{{ for option in options: }}
<tr>
<td>+ {{= option.description }}</td>
<td> ${{= option.price }}</td>
</tr>
{{ pass }}
</table>
</td>
<td><h3>${{= total_price }}</h3></td>
<td><a href="{{= URL(r=request, f='remove_from_cart', args=i) }}">remove</a></td>
</tr>
{{ pass }}
<tr>
<td style="text-align:right"><h3>Balance:</h3></td>
<td><h2>${{= "%.2f" % session.balance }}</h2></td>
</table>
<br/>
<br/>
<form name="google_form" action="https://checkout.google.com/cws/v2/Merchant/{{= merchant_id }}/checkoutForm" id="BB_BuyButtonForm" method="post" name="BB_BuyButtonForm">
{{ for i, (product_id, qty, total_price, product, options) in enumerate(order): }}
<input name="item_name_{{= i }}" type="hidden" value="{{= product.name }}"/>
<input name="item_description_{{= i }}" type="hidden" value="{{= product.description }}"/>
<input name="item_quantity_{{= i }}" type="hidden" value="{{= qty }}"/>
<input name="item_price_{{= i }}" type="hidden" value="{{= total_price }}"/>
<input name="item_weight_{{= i }}" unit="LB" type="hidden" value="{{= product.weight_in_pounds }}"/>
<input name="item_currency_{{= i }}" type="hidden" value="USD"/>
{{ pass }}
<input name="_charset_" type="hidden" value="utf-8"/>
<!-- fill in taxes and shipping options -->
<input alt="" src="https://checkout.google.com/buttons/buy.gif?merchant_id={{=merchant_id}}&w=117&h=48&style=white&variant=text&loc=en_US" type="image" onclick="process(google_form);return false;"/>
</form>
{{ pass }}
<script language="text/javascript">
<!--
function process(form_name) {
i = new Image()
i.src = "/{{= request.application }}/default/empty_cart";
form_name.submit();
}
//-->
</script>
{{ pass }}
|
0707tim-web2pestore
|
views/default/checkout.html
|
HTML
|
gpl2
| 2,421
|
{{ extend 'layout.html' }}
{{ include 'catalog.html' }}
<h1>{{= product.name }}</h1>
<img src="{{= URL(r=request, f='show', args=(product.large_image if product.large_image else product.small_image)) }}" height="200px"/>
{{= product_form }}
<p>{{= XML(product.description) }}</p>
{{ if product.allow_rating and product.rating > 0: }}
{{= '%.1f' % product.rating }}/5.0 rating,
{{ pass }}
{{ if product.quantity_in_stock != UNDEFINED: }}
{{ if product.quantity_in_stock < 1: }}
low stock
{{ else: }}
{{= product.quantity_in_stock }} in stock
{{ pass }}
{{ pass }}
{{ pass }}
<br/>
<br/>
{{ if suggested: }}
<h2>You may also be interested in:</h2>
{{ show(suggested) }}
{{ pass }}
{{ if product.allow_rating: }}
<br/>
{{ if comments: }}
<h2>Visitors' comments</h2>
<p><ul>
{{ for comment in comments: }}
<li>{{= comment.author }} says <i>"{{= comment.body }}"</i></li>
{{ pass }}
</ul>
</p>
{{ pass }}
{{= comment_form }}
{{ pass }}
<script type="text/javascript">
var total_price = {{= product.price }};
function update_price(e, option_price) {
if($(e).is(':checked')) total_price += option_price;
else total_price -= option_price;
$("#total_price").text('$' + Math.round(100*total_price)/100);
}
</script>
|
0707tim-web2pestore
|
views/default/product.html
|
HTML
|
gpl2
| 1,378
|
{{ extend 'layout.html' }}
{{ include 'catalog.html' }}
<h2>Product Categories:</h2>
{{ show(categories, function='category') }}
<br/><br/>
{{ if featured: }}
<h1>Featured Products</h1>
{{ show(featured) }}
{{ pass }}
|
0707tim-web2pestore
|
views/default/index.html
|
HTML
|
gpl2
| 223
|
{{ extend 'layout.html' }}
{{ include 'catalog.html' }}
<h1>Products in {{= category_name }}</h1>
{{ if featured or favourites: }}
{{ show(featured) }}
{{ show(favourites) }}
{{ else: }}
<h2>No products in category {{= category_name }}</h2>
{{ pass }}
|
0707tim-web2pestore
|
views/default/category.html
|
HTML
|
gpl2
| 262
|
{{ extend 'layout.html' }}
{{ import cgi }}
<h1>About Us</h1>
<h2>Our Store</h2>
<p>{{= XML(cgi.escape(mystore.description).replace('\n', '</p><p>')) }}</p>
<h2>Why Buy From Us?</h2>
<p>{{= XML(cgi.escape(mystore.why_buy).replace('\n', '</p><p>')) }}</p>
<h2>Return Policy</h2>
<p>{{= XML(cgi.escape(mystore.return_policy).replace('\n', '</p><p>')) }}</p>
|
0707tim-web2pestore
|
views/default/aboutus.html
|
HTML
|
gpl2
| 363
|
<html>
<head>
<title>Product Image</title>
<script language='javascript'>
var arrTemp=self.location.href.split("?");
var picUrl = (arrTemp.length>0)?arrTemp[1]:"";
var NS = (navigator.appName=="Netscape")?true:false;
function FitPic() {
iWidth = (NS)?window.innerWidth:document.body.clientWidth;
iHeight = (NS)?window.innerHeight:document.body.clientHeight;
iWidth = document.images[0].width - iWidth;
iHeight = document.images[0].height - iHeight;
window.resizeBy(iWidth, iHeight);
self.focus();
};
</script>
</head>
<body bgcolor="#000000" onload='FitPic();' topmargin="0"
marginheight="0" leftmargin="0" marginwidth="0">
<script language='javascript'>
document.write( "<img src='" + picUrl + "' border=0>" );
</script>
</body>
</html>
|
0707tim-web2pestore
|
views/default/popup.html
|
HTML
|
gpl2
| 829
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="keywords" content="{{=response.keywords}}" />
<meta name="description" content="{{=response.description}}" />
<title>{{= response.title or title() }}</title>
<link type="text/css" rel="stylesheet" href="/{{=request.application}}/static/textarea/SyntaxHighlighter.css"></link>
<style>
div.fluid { width: 93% !important; }
div.fixed { width: 800px !important; }
* { margin: 0em; padding: 0em; }
body { background-color: {{= mystore.color_background }}; color: {{= mystore.color_foreground }}; font-size: 10pt; font-family: {{= mystore.font_family }}; }
h1,h2,h3,h4,h5,h6 { font-weight: normal; letter-spacing: -1px; }
h2,h3,h4,h5,h6 { color: {{= mystore.color_foreground }}; }
br.clear { clear: both; }
img.icon { border: 0px; vertical-align: middle; }
img.floatTL { float: left; margin-right: 1.5em; margin-bottom: 1.5em; margin-top: 0.5em; }
a { text-decoration: none; color: {{= mystore.color_link }}; }
a:hover { text-decoration: underline; }
textarea { font-family: courier; }
ul { margin-left: 1.5em; }
li { line-height: 1.5em; }
dd { text-decoration: bold; }
dt { text-decoration:none; margine-left: +10em; }
p { line-height: 1.8em; }
table, tr, td { text-align: left; vertical-align: top; }
#header { width:100%; height:100px; background: {{=mystore.color_header}}; {{if mystore.logo:}}; url('/{{=request.application}}/default/show/{{=mystore.logo}}') repeat-x; {{pass}} }
#header_inner { position: relative; width: 800px; height:70px; margin: 0 auto; }
/* Logo */
#logo { position: absolute; left: 4em; bottom: 0.6em; }
#logo h1 { display: inline; color: {{= mystore.color_foreground }}; font-size: 1.8em; }
#logo h2 { display: inline; color: {{= mystore.color_foreground }}; font-size: 1.3em;}
/* Menu */
#menu { position: absolute; right: 0em; bottom: -2.5em; }
#menu ul { list-style: none; }
#menu li { float: left; }
#menu li a { margin-left: 0.5em; display: block; padding: 0.5em 0.5em 0.5em 0.5em; background: {{= mystore.color_background }} repeat-x; color: {{= mystore.color_link }}; font-weight: bold; font-size: 1.0em; text-decoration: none;}
#menu li a.inactive { background: transparent; color: {{= mystore.color_foreground }}; border: solid 0px {{= mystore.color_link }} border-top: solid 0px {{= mystore.color_link }}; }
/* Main */
#main { background: #fff 0px 1px repeat-x; }
#main_inner p { text-align: justify; margin-bottom: 2.0em; }
#main_inner ul { margin-bottom: 2.0em; }
#main_inner { position: relative; width: 800px; margin: 0 auto; padding-top: 1.0em; }
#main_inner h1 { border-bottom: dotted 1px #E1E1E1; position: relative; font-size: 2.1em; padding-bottom: 0.1em; margin-bottom: 0.8em; }
#main_inner .post { position: relative; }
#main_inner .post h3 { position: relative; font-size: 1.7em; padding-bottom: 1.2em; }
#main_inner .post ul.post_info { list-style: none; position: absolute; top: 3em; font-size: 0.8em; }
#main_inner .post ul.post_info li { background-position: 0em 0.2em; background-repeat: no-repeat; display: inline; padding-left: 18px; }
/* Flash */
#flash { width: 600px; margin: 0 auto; text-align: center; clear: both; border: 1px #000000; background-color: {{= mystore.color_link }}; color: {{= mystore.color_background }}; margin-top: 0.0em; margin-bottom: 1.0em; padding-top: 1.0em; padding-bottom: 1.0em; }
/* Footer */
#footer { width: 800px; margin: 0 auto; text-align: center; clear: both; border-top: dotted 1px #E1E1E1; margin-top: 1.0em; margin-bottom: 1.5em; padding-top: 1.0em; }
/* Search */
input.button { background: #FF6C1F repeat-x; color: {{= mystore.color_background }}; border: solid 1px #DB7623; font-weight: bold; font-size: 0.8em; height: 2.0em; }
input.text { border: solid 1px #F1F1F1; font-size: 1.0em; padding: 0.25em 0.25em 0.25em 0.25em; }
/* LAYOUT - 3 COLUMNS */
/* Primary content */
#primaryContent_3columns { position: relative; margin-right: 34em; }
#columnA_3columns { position: relative; float: left; width: 100%; margin-right: -34em; padding-right: 2em; }
/* Secondary Content */
#secondaryContent_3columns { float: right; }
#columnB_3columns { width: 13.0em; float: left; padding: 0em 2em 0.5em 2em; border-left: dotted 1px #E1E1E1; }
#columnC_3columns { width: 13.0em; float: left; padding: 0em 0em 0.5em 2em; border-left: dotted 1px #E1E1E1; }
/* LAYOUT - 2 COLUMNS */
/* Primary content */
#primaryContent_2columns { position: relative; margin-right: 17em; }
#columnA_2columns { position: relative; float: left; width: 100%; margin-right: -17em; padding-right: 2em; }
/* Secondary Content */
#secondaryContent_2columns { float: right; }
#columnC_2columns { width: 13.0em; float: left; padding: 0em 0em 0.5em 2em; border-left: dotted 1px #E1E1E1; }
/* LAYOUT - COLUMNLESS */
/* Primary content */
#primaryContent_columnless { position: relative; }
#columnA_columnless { position: relative; width: 100%; }
</style>
{{ include 'web2py_ajax.html' }}
</head>
<body>
<div id="header">
<div id="header_inner" class="fixed">
<div id="logo">
<h1><a href="{{= URL(r=request, c='default', f='index') }}">{{= mystore.name }}</a></h1><br/>
<h2>{{= mystore.headline }}</h2>
</div>
{{ if response.menu: }}
<div id="menu">
<ul>
{{ for _name, _active, _link in response.menu: }}
<li><a href="{{= _link }}" {{ if not _active: }}class="inactive"{{ pass }}>{{= _name }}</a></li>
{{ pass }}
</ul>
</div>
{{ pass }}
</div>
</div>
<div id="main">
<div id="main_inner" class="fixed">
<div id="primaryContent_columnless">
<div id="columnA_columnless">
{{ if response.flash: }}
<div id="flash">{{= response.flash }}</div>
{{ pass }}
{{ include }}
</div>
</div>
<div id="footer" class="fixed">
{{= mystore.address }}
</div>
</div>
</div>
</body>
</html>
|
0707tim-web2pestore
|
views/layout.html
|
HTML
|
gpl2
| 6,077
|
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
{{import os
if os.path.exists(os.path.join(request.folder,'static','calendar.js')):}}
<link rel="stylesheet" href="/{{=request.application}}/static/calendar.css" type="text/css" media="screen" title="core css file" charset="utf-8" />
<script src="/{{=request.application}}/static/calendar.js" type="text/javascript" charset="utf-8"></script>
{{pass}}
<script type="text/javascript"><!--
/* Written by Massimo Di Pierro. Here for backward compatibility. */
function popup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) newwindow.focus();
return false;
}
function collapse(id) { $('#'+id).slideToggle(); }
function fade(id,value) { if(value>0) $('#'+id).hide().fadeIn('slow'); else $('#'+id).show().fadeOut('slow'); }
function ajax(u,s,t) {
var query="";
for(i=0; i<s.length; i++) { if(i>0) query=query+"&";
query=query+encodeURIComponent(s[i])+"="+encodeURIComponent(document.getElementById(s[i]).value);
}
$.ajax({type: "POST", url: u, data: query, success: function(msg) { document.getElementById(t).innerHTML=msg; } });
}
String.prototype.reverse = function () {return this.split('').reverse().join('');};
$(document).ready(function() {
$('div.error').hide().slideDown('slow');
$('#flash').hide().slideDown('slow')
$('#flash').click(function() { $(this).fadeOut('slow'); return false; });
$('input.integer').keyup(function(){this.value=this.value.reverse().replace(/[^0-9\-]|\-(?=.)/g,'').reverse();});
$('input.double').keyup(function(){this.value=this.value.reverse().replace(/[^0-9\-\.]|[\-](?=.)|[\.](?=[0-9]*[\.])/g,'').reverse();});
try {$("input.date").focus( function() {Calendar.setup({
inputField: this.id,
ifFormat: "{{=T('%Y-%m-%d')}}",
showsTime: false
}); }); } catch(e) {};
try { $("input.datetime").focus( function() {Calendar.setup({
inputField: this.id,
ifFormat: "{{=T('%Y-%m-%d %H:%M:%S')}}",
showsTime: true,
timeFormat: "24"
}); }); } catch(e) {};
try { $("input.time").clockpick({
starthour : 0,
endhour : 23,
showminutes : true,
military : true
}); } catch(e) {};
});
//--></script>
|
0707tim-web2pestore
|
views/web2py_ajax.html
|
HTML
|
gpl2
| 2,230
|
{{extend 'layout.html'}}
<script><!--
$(document).ready(function(){
$("table.sortable tbody tr").mouseover( function() {
$(this).addClass("highlight"); }).mouseout( function() {
$(this).removeClass("highlight"); });
$('table.sortable tbody tr:odd').addClass('odd');
$('table.sortable tbody tr:even').addClass('even');
});
//--></script>
{{if request.function=='index':}}
<h1>{{=T("Available databases and tables")}}</h1>
{{if not databases:}}{{=T("No databases in this application")}}{{pass}}
{{for db in sorted(databases):}}
{{for table in databases[db].tables:}}
<h2>{{=A("%s.%s"%(db,table),_href=URL(r=request,f='select',args=[db],vars=dict(query='%s.%s.id>0'%(db,table))))}}</h2>
[ {{=A(str(T('insert new'))+' '+table,_href=URL(r=request,f='insert',args=[db,table]))}} ]
<br /><br />
{{pass}}
{{pass}}
{{elif request.function=='select':}}
<h1>{{=XML(str(T("database %s select"))%A(request.args[0],_href=URL(r=request,f='index'))) }}
</h1>
{{if table:}}
[ {{=A(str(T('insert new %s'))%table,_href=URL(r=request,f='insert',args=[request.args[0],table]))}} ]<br/><br/>
<h2>{{=T("Rows in table")}}</h2><br/>
{{else:}}
<h2>{{=T("Rows selected")}}</h2><br/>
{{pass}}
{{=form}}
<p>{{=T('The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.')}}<br/>
{{=T('Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.')}}<br/>
{{=T('"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN')}}</p>
<br/><br/>
<h3>{{=nrows}} {{=T("selected")}}</h3>
{{if start>0:}}[ {{=A(T('previous 100 rows'),_href=URL(r=request,f='select',args=request.args[0],vars=dict(start=start-100)))}} ]{{pass}}
{{if stop<nrows:}}[ {{=A(T('next 100 rows'),_href=URL(r=request,f='select',args=request.args[0],vars=dict(start=start+100)))}} ]{{pass}}
{{if rows:}}
<div style="overflow: auto;" width="80%">
{{linkto=URL(r=request,f='update',args=request.args[0])}}
{{upload=URL(r=request,f='download',args=request.args[0])}}
{{=SQLTABLE(rows,linkto,upload,orderby=True,_class='sortable')}}
</div>
{{pass}}
<br/><br/><h2>{{=T("Import/Export")}}</h2><br/>
[ <a href="{{=URL(r=request,f='csv',args=request.args[0],vars=dict(query=query))}}">{{=T("export as csv file")}}</a> ]
{{if table:}}
{{=FORM(str(T('or import from csv file'))+" ",INPUT(_type='file',_name='csvfile'),INPUT(_type='hidden',_value=table,_name='table'),INPUT(_type='submit',_value='import'))}}
{{pass}}
{{elif request.function=='insert':}}
<h1>{{=T("database")}} {{=A(request.args[0],_href=URL(r=request,f='index'))}}
{{=T("table")}} {{=A(request.args[1],_href=URL(r=request,f='select',args=request.args[0],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2]))))}}
</h1>
<h2>{{=T("New Record")}}</h2><br/>
{{=form}}
{{elif request.function=='update':}}
<h1>{{=T("database")}} {{=A(request.args[0],_href=URL(r=request,f='index'))}}
{{=T("table")}} {{=A(request.args[1],_href=URL(r=request,f='select',args=request.args[0],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2]))))}}
{{=T("record id")}} {{=A(request.args[2],_href=URL(r=request,f='update',args=request.args[:3]))}}
</h1>
<h2>{{=T("Edit current record")}}</h2><br/><br/>{{=form}}
{{elif request.function=='state':}}
<h1>{{=T("Internal State")}}</h1>
<h2>{{=T("Current request")}}</h2>
{{=BEAUTIFY(request)}}
<br/><h2>{{=T("Current response")}}</h2>
{{=BEAUTIFY(response)}}
<br/><h2>{{=T("Current session")}}</h2>
{{=BEAUTIFY(session)}}
{{pass}}
|
0707tim-web2pestore
|
views/appadmin.html
|
HTML
|
gpl2
| 3,738
|
{{extend 'layout.html' }}
<script src="/{{= request.application }}/static/sorttable.js"></script>
<style>
table.sortable thead {
background-color:#eee;
color:#666666;
font-weight: bold;
cursor: default;
}
</style>
{{ try: }}{{= uplink }}{{ except: }}{{ pass }}
<h1>
{{ if request.function == 'state': }}
Internal state
{{ else: }}
{{ if len(request.args) >= 1: }}
database
{{ if not request.vars.query: }}table {{= A(request.args[1],_href=URL(r=request, f='select/%s/%s' % tuple(request.args[:2]))) }} select {{ else: }} generic select/update/delete{{ pass }}
{{ if len(request.args) == 3: }}
record id {{= A(request.args[2],_href=URL(r=request, f='update/%s/%s/%s' % tuple(request.args[:3]))) }}
{{ pass }}
{{ else: }}
Manage store
{{ pass }}
{{ pass }}
</h1>
{{ if request.function == 'index': }}
<h2>{{= A("Setup", _href='/%s/manage/setup'%request.application) }}</h2>
<i>Here you setup general store information</i>
<br/><br/>
<h2>{{= A("Store Categrories", _href=URL(r=request, f='select/store/category')) }}</h2>
<i>Here you manage the categories of products</i>
<br/><br/>
<h2>{{= A("Store Products", _href=URL(r=request, f='select/store/product')) }}</h2>
<i>Here you manage the actual products you sells</i>
<br/><br/>
<h2>{{= A("Store Comments", _href=URL(r=request, f='select/store/comment')) }}</h2>
<i>Here you manage the comments posted by visitors</i>
<br/><br/>
<h2>{{= A("Cleanup Temporary Files", _href=URL(r=request, f='cleanup')) }}</h2>
<i>This is a maintenance function, run it once a week.</i>
<br/><br/>
<br/><br/>
{{ pass }}
{{ if request.function == 'select' and len(request.args) > 1: }}
[ {{= A('insert new %s' % request.args[1], _href=URL(r=request, f='insert/%s/%s' % tuple(request.args[:2]))) }} ]<br/><br/>
<h2>Rows in table</h2><br/>
{{ elif request.function=='select' and len(request.args) == 1: }}
<h2>Rows selected</h2><br/>
{{ pass }}
{{ if request.function == 'select' and len(request.args) >= 1: }}
<form action="{{= URL(r=request,args=request.args[:1]) }}" method="post">
<table>
<tr><td width="150px">FILTER CONDITION:</td><td><input type="text" value="{{= query }}" name="query" size="60"/><input type="submit" value="apply"/></td></tr>
{{ if len(request.args) == 1: }}
<tr><td>UPDATE STRING:</td><td><input type="text" value="" name="update_string"/> or DELETE ALL: <input type="checkbox" name="delete_all"/> (sure?<select name="delete_all_sure"/><option selected>no</option><option>yes</option></select>)<br/><i>(The SQL FILTER is a condition like "table1.field1='value'". Something like "table1.field1=table2.field2" results in a SQL JOIN. Use AND, OR and (...) to build more complex filters. The UPDATE STRING is an optional expression like "field1='newvalue'". You cannot update or delete the results of a JOIN)</i>
</td></tr>
{{ pass }}
</table>
</form>
<br/> <br/>
{{ if start > 0: }}[ {{= A('previous 100 records',_href=URL(r=request, f='select/%s?query=%s&start=%s' % ('/'.join(request.args), query, start-100))) }} ]{{ pass }}
{{ if nrecords == 100: }}[ {{= A('next 100 records',_href=URL(r=request, f='select/%s?query=%s&start=%s' % ('/'.join(request.args), query, start+100))) }} ]{{ pass }}
{{= records }}
<br/><br/><h2>CSV import/export</h2><br/>
[ <a href="{{= URL(r=request,f='csv',vars=dict(dbname=request.args[0],query=query)) }}">export as csv file</a> ]
{{ if len(request.args) == 2: }}
{{= FORM('or import from csv file ', INPUT(_type='file', _name='csvfile'),INPUT(_type='submit', _value='import')) }}
{{ pass }}
{{ pass }}
{{ if request.function == 'insert' and len(request.args) > 1: }}
<h2>New Record</h2><br/>
{{= form }}
{{ pass }}
{{ if request.function == 'update' and len(request.args) > 2: }}
<h2>Edit current record</h2><br/><br/>{{= form }}
{{ pass }}
{{ if request.function == 'state': }}
<h2>Current request</h2>
{{= BEAUTIFY(request) }}
<br/><h2>Current response</h2>
{{= BEAUTIFY(response) }}
<br/><h2>Current session</h2>
{{= BEAUTIFY(session) }}
{{ pass }}
|
0707tim-web2pestore
|
views/manage.html
|
HTML
|
gpl2
| 4,184
|
{{ extend 'layout.html' }}
{{= BEAUTIFY(response._vars) }}
|
0707tim-web2pestore
|
views/generic.html
|
HTML
|
gpl2
| 58
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.tesseract.android;
import android.graphics.Bitmap;
import android.graphics.Rect;
import com.googlecode.leptonica.android.Pix;
import com.googlecode.leptonica.android.ReadFile;
import java.io.File;
/**
* Java interface for the Tesseract OCR engine. Does not implement all available
* JNI methods, but does implement enough to be useful. Comments are adapted
* from original Tesseract source.
*
* @author alanv@google.com (Alan Viverette)
*/
public class TessBaseAPI {
/**
* Used by the native implementation of the class.
*/
private int mNativeData;
static {
System.loadLibrary("lept");
System.loadLibrary("tess");
nativeClassInit();
}
/** Fully automatic page segmentation. */
public static final int PSM_AUTO = 0;
/** Assume a single column of text of variable sizes. */
public static final int PSM_SINGLE_COLUMN = 1;
/** Assume a single uniform block of text. (Default) */
public static final int PSM_SINGLE_BLOCK = 2;
/** Treat the image as a single text line. */
public static final int PSM_SINGLE_LINE = 3;
/** Treat the image as a single word. */
public static final int PSM_SINGLE_WORD = 4;
/** Treat the image as a single character. */
public static final int PSM_SINGLE_CHAR = 5;
/** Default accuracy versus speed mode. */
public static final int AVS_FASTEST = 0;
/** Slowest and most accurate mode. */
public static final int AVS_MOST_ACCURATE = 100;
/** Whitelist of characters to recognize. */
public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist";
/** Blacklist of characters to not recognize. */
public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist";
/** Accuracy versus speed setting. */
public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed";
/**
* Constructs an instance of TessBaseAPI.
*/
public TessBaseAPI() {
nativeConstruct();
}
/**
* Called by the GC to clean up the native data that we set up when we
* construct the object.
*/
@Override
protected void finalize() throws Throwable {
try {
nativeFinalize();
} finally {
super.finalize();
}
}
/**
* Initializes the Tesseract engine with a specified language model. Returns
* <code>true</code> on success.
* <p>
* Instances are now mostly thread-safe and totally independent, but some
* global parameters remain. Basically it is safe to use multiple
* TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable
* on some of the Params in classify and textord. If you do, then the effect
* will be to change it for all your instances.
* <p>
* The datapath must be the name of the parent directory of tessdata and
* must end in / . Any name after the last / will be stripped. The language
* is (usually) an ISO 639-3 string or <code>null</code> will default to eng.
* It is entirely safe (and eventually will be efficient too) to call Init
* multiple times on the same instance to change language, or just to reset
* the classifier.
* <p>
* <b>WARNING:</b> On changing languages, all Tesseract parameters are reset
* back to their default values. (Which may vary between languages.)
* <p>
* If you have a rare need to set a Variable that controls initialization
* for a second call to Init you should explicitly call End() and then use
* SetVariable before Init. This is only a very rare use case, since there
* are very few uses that require any parameters to be set before Init.
*
* @param datapath the parent directory of tessdata ending in a forward
* slash
* @param language (optional) an ISO 639-3 string representing the language
* @return <code>true</code> on success
*/
public boolean init(String datapath, String language) {
if (datapath == null)
throw new IllegalArgumentException("Data path must not be null!");
if (!datapath.endsWith(File.separator))
datapath += File.separator;
File tessdata = new File(datapath + "tessdata");
if (!tessdata.exists() || !tessdata.isDirectory())
throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
return nativeInit(datapath, language);
}
/**
* Frees up recognition results and any stored image data, without actually
* freeing any recognition data that would be time-consuming to reload.
* Afterwards, you must call SetImage or SetRectangle before doing any
* Recognize or Get* operation.
*/
public void clear() {
nativeClear();
}
/**
* Closes down tesseract and free up all memory. End() is equivalent to
* destructing and reconstructing your TessBaseAPI.
* <p>
* Once End() has been used, none of the other API functions may be used
* other than Init and anything declared above it in the class definition.
*/
public void end() {
nativeEnd();
}
/**
* Set the value of an internal "variable" (of either old or new types).
* Supply the name of the variable and the value as a string, just as you
* would in a config file.
* <p>
* Example: <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code>
* <p>
* setVariable() may be used before open(), but settings will revert to
* defaults on close().
*
* @param var name of the variable
* @param value value to set
* @return false if the name lookup failed
*/
public boolean setVariable(String var, String value) {
return nativeSetVariable(var, value);
}
/**
* Sets the page segmentation mode. This controls how much processing the
* OCR engine will perform before recognizing text.
*
* @param mode the page segmentation mode to set
*/
public void setPageSegMode(int mode) {
nativeSetPageSegMode(mode);
}
/**
* Sets debug mode. This controls how much information is displayed in the
* log during recognition.
*
* @param enabled <code>true</code> to enable debugging mode
*/
public void setDebug(boolean enabled) {
nativeSetDebug(enabled);
}
/**
* Restricts recognition to a sub-rectangle of the image. Call after
* SetImage. Each SetRectangle clears the recogntion results so multiple
* rectangles can be recognized with the same image.
*
* @param rect the bounding rectangle
*/
public void setRectangle(Rect rect) {
setRectangle(rect.left, rect.top, rect.width(), rect.height());
}
/**
* Restricts recognition to a sub-rectangle of the image. Call after
* SetImage. Each SetRectangle clears the recogntion results so multiple
* rectangles can be recognized with the same image.
*
* @param left the left bound
* @param top the right bound
* @param width the width of the bounding box
* @param height the height of the bounding box
*/
public void setRectangle(int left, int top, int width, int height) {
nativeSetRectangle(left, top, width, height);
}
/**
* Provides an image for Tesseract to recognize.
*
* @param file absolute path to the image file
*/
public void setImage(File file) {
Pix image = ReadFile.readFile(file);
if (image == null) {
throw new RuntimeException("Failed to read image file");
}
nativeSetImagePix(image.getNativePix());
}
/**
* Provides an image for Tesseract to recognize. Does not copy the image
* buffer. The source image must persist until after Recognize or
* GetUTF8Chars is called.
*
* @param bmp bitmap representation of the image
*/
public void setImage(Bitmap bmp) {
Pix image = ReadFile.readBitmap(bmp);
if (image == null) {
throw new RuntimeException("Failed to read bitmap");
}
nativeSetImagePix(image.getNativePix());
}
/**
* Provides a Leptonica pix format image for Tesseract to recognize. Clones
* the pix object. The source image may be destroyed immediately after
* SetImage is called, but its contents may not be modified.
*
* @param image Leptonica pix representation of the image
*/
public void setImage(Pix image) {
nativeSetImagePix(image.getNativePix());
}
/**
* Provides an image for Tesseract to recognize. Copies the image buffer.
* The source image may be destroyed immediately after SetImage is called.
* SetImage clears all recognition results, and sets the rectangle to the
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
*
* @param imagedata byte representation of the image
* @param width image width
* @param height image height
* @param bpp bytes per pixel
* @param bpl bytes per line
*/
public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) {
nativeSetImageBytes(imagedata, width, height, bpp, bpl);
}
/**
* The recognized text is returned as a String which is coded as UTF8.
*
* @return the recognized text
*/
public String getUTF8Text() {
// Trim because the text will have extra line breaks at the end
String text = nativeGetUTF8Text();
return text.trim();
}
/**
* Returns the mean confidence of text recognition.
*
* @return the mean confidence
*/
public int meanConfidence() {
return nativeMeanConfidence();
}
/**
* Returns all word confidences (between 0 and 100) in an array. The number
* of confidences should correspond to the number of space-delimited words
* in GetUTF8Text().
*
* @return an array of word confidences (between 0 and 100) for each
* space-delimited word returned by GetUTF8Text()
*/
public int[] wordConfidences() {
int[] conf = nativeWordConfidences();
// We shouldn't return null confidences
if (conf == null)
conf = new int[0];
return conf;
}
// ******************
// * Native methods *
// ******************
/**
* Initializes static native data. Must be called on object load.
*/
private static native void nativeClassInit();
/**
* Initializes native data. Must be called on object construction.
*/
private native void nativeConstruct();
/**
* Finalizes native data. Must be called on object destruction.
*/
private native void nativeFinalize();
private native boolean nativeInit(String datapath, String language);
private native void nativeClear();
private native void nativeEnd();
private native void nativeSetImageBytes(
byte[] imagedata, int width, int height, int bpp, int bpl);
private native void nativeSetImagePix(int nativePix);
private native void nativeSetRectangle(int left, int top, int width, int height);
private native String nativeGetUTF8Text();
private native int nativeMeanConfidence();
private native int[] nativeWordConfidences();
private native boolean nativeSetVariable(String var, String value);
private native void nativeSetDebug(boolean debug);
private native void nativeSetPageSegMode(int mode);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/tesseract/android/TessBaseAPI.java
|
Java
|
asf20
| 12,348
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
import android.graphics.Rect;
/**
* Java representation of a native Leptonica PIX object.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Pix {
static {
System.loadLibrary("lept");
}
/** Index of the image width within the dimensions array. */
public static final int INDEX_W = 0;
/** Index of the image height within the dimensions array. */
public static final int INDEX_H = 1;
/** Index of the image bit-depth within the dimensions array. */
public static final int INDEX_D = 2;
/** Package-accessible pointer to native pix */
final int mNativePix;
private boolean mRecycled;
/**
* Creates a new Pix wrapper for the specified native PIX object. Never call
* this twice on the same native pointer, because finalize() will attempt to
* free native memory twice.
*
* @param nativePix A pointer to the native PIX object.
*/
public Pix(int nativePix) {
mNativePix = nativePix;
mRecycled = false;
}
public Pix(int width, int height, int depth) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Pix width and height must be > 0");
} else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16
&& depth != 24 && depth != 32) {
throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32");
}
mNativePix = nativeCreatePix(width, height, depth);
mRecycled = false;
}
/**
* Returns a pointer to the native Pix object. This is used by native code
* and is only valid within the same process in which the Pix was created.
*
* @return a native pointer to the Pix object
*/
public int getNativePix() {
return mNativePix;
}
/**
* Return the raw bytes of the native PIX object. You can reconstruct the
* Pix from this data using createFromPix().
*
* @return a copy of this PIX object's raw data
*/
public byte[] getData() {
int size = nativeGetDataSize(mNativePix);
byte[] buffer = new byte[size];
if (!nativeGetData(mNativePix, buffer)) {
throw new RuntimeException("native getData failed");
}
return buffer;
}
/**
* Returns an array of this image's dimensions. See Pix.INDEX_* for indices.
*
* @return an array of this image's dimensions or <code>null</code> on
* failure
*/
public int[] getDimensions() {
int[] dimensions = new int[4];
if (getDimensions(dimensions)) {
return dimensions;
}
return null;
}
/**
* Fills an array with this image's dimensions. The array must be at least 3
* elements long.
*
* @param dimensions An integer array with at least three elements.
* @return <code>true</code> on success
*/
public boolean getDimensions(int[] dimensions) {
return nativeGetDimensions(mNativePix, dimensions);
}
/**
* Returns a clone of this Pix. This does NOT create a separate copy, just a
* new pointer that can be recycled without affecting other clones.
*
* @return a clone (shallow copy) of the Pix
*/
@Override
public Pix clone() {
int nativePix = nativeClone(mNativePix);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
/**
* Returns a deep copy of this Pix that can be modified without affecting
* the original Pix.
*
* @return a copy of the Pix
*/
public Pix copy() {
int nativePix = nativeCopy(mNativePix);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
/**
* Inverts this Pix in-place.
*
* @return <code>true</code> on success
*/
public boolean invert() {
return nativeInvert(mNativePix);
}
/**
* Releases resources and frees any memory associated with this Pix. You may
* not modify or access the pix after calling this method.
*/
public void recycle() {
if (!mRecycled) {
nativeDestroy(mNativePix);
mRecycled = true;
}
}
@Override
protected void finalize() throws Throwable {
recycle();
super.finalize();
}
/**
* Creates a new Pix from raw Pix data obtained from getData().
*
* @param pixData Raw pix data obtained from getData().
* @param width The width of the original Pix.
* @param height The height of the original Pix.
* @param depth The bit-depth of the original Pix.
* @return a new Pix or <code>null</code> on error
*/
public static Pix createFromPix(byte[] pixData, int width, int height, int depth) {
int nativePix = nativeCreateFromData(pixData, width, height, depth);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
/**
* Returns a Rect with the width and height of this Pix.
*
* @return a Rect with the width and height of this Pix
*/
public Rect getRect() {
int w = getWidth();
int h = getHeight();
return new Rect(0, 0, w, h);
}
/**
* Returns the width of this Pix.
*
* @return the width of this Pix
*/
public int getWidth() {
return nativeGetWidth(mNativePix);
}
/**
* Returns the height of this Pix.
*
* @return the height of this Pix
*/
public int getHeight() {
return nativeGetHeight(mNativePix);
}
/**
* Returns the depth of this Pix.
*
* @return the depth of this Pix
*/
public int getDepth() {
return nativeGetDepth(mNativePix);
}
/**
* Returns the {@link android.graphics.Color} at the specified location.
*
* @param x The x coordinate (0...width-1) of the pixel to return.
* @param y The y coordinate (0...height-1) of the pixel to return.
* @return The argb {@link android.graphics.Color} at the specified
* coordinate.
* @throws IllegalArgumentException If x, y exceeds the image bounds.
*/
public int getPixel(int x, int y) {
if (x < 0 || x >= getWidth()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
} else if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
}
return nativeGetPixel(mNativePix, x, y);
}
/**
* Sets the {@link android.graphics.Color} at the specified location.
*
* @param x The x coordinate (0...width-1) of the pixel to set.
* @param y The y coordinate (0...height-1) of the pixel to set.
* @param color The argb {@link android.graphics.Color} to set at the
* specified coordinate.
* @throws IllegalArgumentException If x, y exceeds the image bounds.
*/
public void setPixel(int x, int y, int color) {
if (x < 0 || x >= getWidth()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
} else if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
}
nativeSetPixel(mNativePix, x, y, color);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeCreatePix(int w, int h, int d);
private static native int nativeCreateFromData(byte[] data, int w, int h, int d);
private static native boolean nativeGetData(int nativePix, byte[] data);
private static native int nativeGetDataSize(int nativePix);
private static native int nativeClone(int nativePix);
private static native int nativeCopy(int nativePix);
private static native boolean nativeInvert(int nativePix);
private static native void nativeDestroy(int nativePix);
private static native boolean nativeGetDimensions(int nativePix, int[] dimensions);
private static native int nativeGetWidth(int nativePix);
private static native int nativeGetHeight(int nativePix);
private static native int nativeGetDepth(int nativePix);
private static native int nativeGetPixel(int nativePix, int x, int y);
private static native void nativeSetPixel(int nativePix, int x, int y, int color);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Pix.java
|
Java
|
asf20
| 9,231
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
/**
* Image input and output methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class ReadFile {
static {
System.loadLibrary("lept");
}
/**
* Creates a 32bpp Pix object from encoded data. Supported formats are BMP
* and JPEG.
*
* @param encodedData JPEG or BMP encoded byte data.
* @return a 32bpp Pix object
*/
public static Pix readMem(byte[] encodedData) {
if (encodedData == null)
throw new IllegalArgumentException("Image data byte array must be non-null");
final BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length,
opts);
final Pix pix = readBitmap(bmp);
bmp.recycle();
return pix;
}
/**
* Creates an 8bpp Pix object from raw 8bpp grayscale pixels.
*
* @param pixelData 8bpp grayscale pixel data.
* @param width The width of the input image.
* @param height The height of the input image.
* @return an 8bpp Pix object
*/
public static Pix readBytes8(byte[] pixelData, int width, int height) {
if (pixelData == null)
throw new IllegalArgumentException("Byte array must be non-null");
if (width <= 0)
throw new IllegalArgumentException("Image width must be greater than 0");
if (height <= 0)
throw new IllegalArgumentException("Image height must be greater than 0");
if (pixelData.length < width * height)
throw new IllegalArgumentException("Array length does not match dimensions");
int nativePix = nativeReadBytes8(pixelData, width, height);
if (nativePix == 0)
throw new RuntimeException("Failed to read pix from memory");
return new Pix(nativePix);
}
/**
* Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels.
* Width and height be identical to the input Pix.
*
* @param pixs The Pix whose bytes will be replaced.
* @param pixelData 8bpp grayscale pixel data.
* @param width The width of the input image.
* @param height The height of the input image.
* @return an 8bpp Pix object
*/
public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (pixelData == null)
throw new IllegalArgumentException("Byte array must be non-null");
if (width <= 0)
throw new IllegalArgumentException("Image width must be greater than 0");
if (height <= 0)
throw new IllegalArgumentException("Image height must be greater than 0");
if (pixelData.length < width * height)
throw new IllegalArgumentException("Array length does not match dimensions");
if (pixs.getWidth() != width)
throw new IllegalArgumentException("Source pix width does not match image width");
if (pixs.getHeight() != height)
throw new IllegalArgumentException("Source pix width does not match image width");
return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height);
}
/**
* Creates a Pixa object from encoded files in a directory. Supported
* formats are BMP and JPEG.
*
* @param dir The directory containing the files.
* @param prefix The prefix of the files to load into a Pixa.
* @return a Pixa object containing one Pix for each file
*/
public static Pixa readFiles(File dir, String prefix) {
if (dir == null)
throw new IllegalArgumentException("Directory must be non-null");
if (!dir.exists())
throw new IllegalArgumentException("Directory does not exist");
if (!dir.canRead())
throw new IllegalArgumentException("Cannot read directory");
// TODO: Remove or fix this.
throw new RuntimeException("readFiles() is not current supported");
}
/**
* Creates a Pix object from encoded file data. Supported formats are BMP
* and JPEG.
*
* @param file The JPEG or BMP-encoded file to read in as a Pix.
* @return a Pix object
*/
public static Pix readFile(File file) {
if (file == null)
throw new IllegalArgumentException("File must be non-null");
if (!file.exists())
throw new IllegalArgumentException("File does not exist");
if (!file.canRead())
throw new IllegalArgumentException("Cannot read file");
final BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
final Pix pix = readBitmap(bmp);
bmp.recycle();
return pix;
}
/**
* Creates a Pix object from Bitmap data. Currently supports only
* ARGB_8888-formatted bitmaps.
*
* @param bmp The Bitmap object to convert to a Pix.
* @return a Pix object
*/
public static Pix readBitmap(Bitmap bmp) {
if (bmp == null)
throw new IllegalArgumentException("Bitmap must be non-null");
if (bmp.getConfig() != Bitmap.Config.ARGB_8888)
throw new IllegalArgumentException("Bitmap config must be ARGB_8888");
int nativePix = nativeReadBitmap(bmp);
if (nativePix == 0)
throw new RuntimeException("Failed to read pix from bitmap");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeReadMem(byte[] data, int size);
private static native int nativeReadBytes8(byte[] data, int w, int h);
private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h);
private static native int nativeReadFiles(String dirname, String prefix);
private static native int nativeReadFile(String filename);
private static native int nativeReadBitmap(Bitmap bitmap);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/ReadFile.java
|
Java
|
asf20
| 6,967
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Wrapper for Leptonica's native BOX.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Box {
static {
System.loadLibrary("lept");
}
/** The index of the X coordinate within the geometry array. */
public static final int INDEX_X = 0;
/** The index of the Y coordinate within the geometry array. */
public static final int INDEX_Y = 1;
/** The index of the width within the geometry array. */
public static final int INDEX_W = 2;
/** The index of the height within the geometry array. */
public static final int INDEX_H = 3;
/**
* A pointer to the native Box object. This is used internally by native
* code.
*/
final int mNativeBox;
private boolean mRecycled = false;
/**
* Creates a new Box wrapper for the specified native BOX.
*
* @param nativeBox A pointer to the native BOX.
*/
Box(int nativeBox) {
mNativeBox = nativeBox;
mRecycled = false;
}
/**
* Creates a box with the specified geometry. All dimensions should be
* non-negative and specified in pixels.
*
* @param x X-coordinate of the top-left corner of the box.
* @param y Y-coordinate of the top-left corner of the box.
* @param w Width of the box.
* @param h Height of the box.
*/
public Box(int x, int y, int w, int h) {
if (x < 0 || y < 0 || w < 0 || h < 0) {
throw new IllegalArgumentException("All box dimensions must be non-negative");
}
int nativeBox = nativeCreate(x, y, w, h);
if (nativeBox == 0) {
throw new OutOfMemoryError();
}
mNativeBox = nativeBox;
mRecycled = false;
}
/**
* Returns the box's x-coordinate in pixels.
*
* @return The box's x-coordinate in pixels.
*/
public int getX() {
return nativeGetX(mNativeBox);
}
/**
* Returns the box's y-coordinate in pixels.
*
* @return The box's y-coordinate in pixels.
*/
public int getY() {
return nativeGetY(mNativeBox);
}
/**
* Returns the box's width in pixels.
*
* @return The box's width in pixels.
*/
public int getWidth() {
return nativeGetWidth(mNativeBox);
}
/**
* Returns the box's height in pixels.
*
* @return The box's height in pixels.
*/
public int getHeight() {
return nativeGetHeight(mNativeBox);
}
/**
* Returns an array containing the coordinates of this box. See INDEX_*
* constants for indices.
*
* @return an array of box oordinates
*/
public int[] getGeometry() {
int[] geometry = new int[4];
if (getGeometry(geometry)) {
return geometry;
}
return null;
}
/**
* Fills an array containing the coordinates of this box. See INDEX_*
* constants for indices.
*
* @param geometry A 4+ element integer array to fill with coordinates.
* @return <code>true</code> on success
*/
public boolean getGeometry(int[] geometry) {
if (geometry.length < 4) {
throw new IllegalArgumentException("Geometry array must be at least 4 elements long");
}
return nativeGetGeometry(mNativeBox, geometry);
}
/**
* Releases resources and frees any memory associated with this Box.
*/
public void recycle() {
if (!mRecycled) {
nativeDestroy(mNativeBox);
mRecycled = true;
}
}
@Override
protected void finalize() throws Throwable {
recycle();
super.finalize();
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeCreate(int x, int y, int w, int h);
private static native int nativeGetX(int nativeBox);
private static native int nativeGetY(int nativeBox);
private static native int nativeGetWidth(int nativeBox);
private static native int nativeGetHeight(int nativeBox);
private static native void nativeDestroy(int nativeBox);
private static native boolean nativeGetGeometry(int nativeBox, int[] geometry);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Box.java
|
Java
|
asf20
| 4,880
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Image bit-depth conversion methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Convert {
static {
System.loadLibrary("lept");
}
/**
* Converts an image of any bit depth to 8-bit grayscale.
*
* @param pixs Source pix of any bit-depth.
* @return a new Pix image or <code>null</code> on error
*/
public static Pix convertTo8(Pix pixs) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeConvertTo8(pixs.mNativePix);
if (nativePix == 0)
throw new RuntimeException("Failed to natively convert pix");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeConvertTo8(int nativePix);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Convert.java
|
Java
|
asf20
| 1,506
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
import android.graphics.Rect;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Java representation of a native PIXA object. This object contains multiple
* PIX objects and their associated bounding BOX objects.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Pixa implements Iterable<Pix> {
static {
System.loadLibrary("lept");
}
/** A pointer to the native PIXA object. This is used internally by native code. */
final int mNativePixa;
/** The specified width of this Pixa. */
final int mWidth;
/** The specified height of this Pixa. */
final int mHeight;
private boolean mRecycled;
/**
* Creates a new Pixa with the specified minimum capacity. The Pixa will
* expand automatically as new Pix are added.
*
* @param size The minimum capacity of this Pixa.
* @return a new Pixa or <code>null</code> on error
*/
public static Pixa createPixa(int size) {
return createPixa(size, 0, 0);
}
/**
* Creates a new Pixa with the specified minimum capacity. The Pixa will
* expand automatically as new Pix are added.
* <p>
* If non-zero, the specified width and height will be used to specify the
* bounds of output images. *
*
* @param size The minimum capacity of this Pixa.
* @param width (Optional) The width of this Pixa, use 0 for default.
* @param height (Optional) The height of this Pixa, use 0 for default.
* @return a new Pixa or <code>null</code> on error
*/
public static Pixa createPixa(int size, int width, int height) {
int nativePixa = nativeCreate(size);
if (nativePixa == 0) {
throw new OutOfMemoryError();
}
return new Pixa(nativePixa, width, height);
}
/**
* Creates a wrapper for the specified native Pixa pointer.
*
* @param nativePixa Native pointer to a PIXA object.
* @param width The width of the PIXA.
* @param height The height of the PIXA.
*/
public Pixa(int nativePixa, int width, int height) {
mNativePixa = nativePixa;
mWidth = width;
mHeight = height;
mRecycled = false;
}
/**
* Returns a pointer to the native PIXA object. This is used by native code.
*
* @return a pointer to the native PIXA object
*/
public int getNativePixa() {
return mNativePixa;
}
/**
* Creates a shallow copy of this Pixa. Contained Pix are cloned, and the
* resulting Pixa may be recycled separately from the original.
*
* @return a shallow copy of this Pixa
*/
public Pixa copy() {
int nativePixa = nativeCopy(mNativePixa);
if (nativePixa == 0) {
throw new OutOfMemoryError();
}
return new Pixa(nativePixa, mWidth, mHeight);
}
/**
* Sorts this Pixa using the specified field and order. See
* Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or
* Constants.L_SORT_DECREASING.
*
* @param field The field to sort by. See Constants.L_SORT_BY_*.
* @param order The order in which to sort. Must be either
* Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING.
* @return a sorted copy of this Pixa
*/
public Pixa sort(int field, int order) {
int nativePixa = nativeSort(mNativePixa, field, order);
if (nativePixa == 0) {
throw new OutOfMemoryError();
}
return new Pixa(nativePixa, mWidth, mHeight);
}
/**
* Returns the number of elements in this Pixa.
*
* @return the number of elements in this Pixa
*/
public int size() {
return nativeGetCount(mNativePixa);
}
/**
* Recycles this Pixa and frees natively allocated memory. You may not
* access or modify the Pixa after calling this method.
* <p>
* Any Pix obtained from this Pixa or copies of this Pixa will still be
* accessible until they are explicitly recycled or finalized by the garbage
* collector.
*/
public synchronized void recycle() {
if (!mRecycled) {
nativeDestroy(mNativePixa);
mRecycled = true;
}
}
@Override
protected void finalize() throws Throwable {
recycle();
super.finalize();
}
/**
* Merges the contents of another Pixa into this one.
*
* @param otherPixa
* @return <code>true</code> on success
*/
public boolean join(Pixa otherPixa) {
return nativeJoin(mNativePixa, otherPixa.mNativePixa);
}
/**
* Adds a Pix to this Pixa.
*
* @param pix The Pix to add.
* @param mode The mode in which to add this Pix, typically
* Constants.L_CLONE.
*/
public void addPix(Pix pix, int mode) {
nativeAddPix(mNativePixa, pix.mNativePix, mode);
}
/**
* Adds a Box to this Pixa.
*
* @param box The Box to add.
* @param mode The mode in which to add this Box, typically
* Constants.L_CLONE.
*/
public void addBox(Box box, int mode) {
nativeAddBox(mNativePixa, box.mNativeBox, mode);
}
/**
* Adds a Pix and associated Box to this Pixa.
*
* @param pix The Pix to add.
* @param box The Box to add.
* @param mode The mode in which to add this Pix and Box, typically
* Constants.L_CLONE.
*/
public void add(Pix pix, Box box, int mode) {
nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode);
}
/**
* Returns the Box at the specified index, or <code>null</code> on error.
*
* @param index The index of the Box to return.
* @return the Box at the specified index, or <code>null</code> on error
*/
public Box getBox(int index) {
int nativeBox = nativeGetBox(mNativePixa, index);
if (nativeBox == 0) {
return null;
}
return new Box(nativeBox);
}
/**
* Returns the Pix at the specified index, or <code>null</code> on error.
*
* @param index The index of the Pix to return.
* @return the Pix at the specified index, or <code>null</code> on error
*/
public Pix getPix(int index) {
int nativePix = nativeGetPix(mNativePixa, index);
if (nativePix == 0) {
return null;
}
return new Pix(nativePix);
}
/**
* Returns the width of this Pixa, or 0 if one was not set when it was
* created.
*
* @return the width of this Pixa, or 0 if one was not set when it was
* created
*/
public int getWidth() {
return mWidth;
}
/**
* Returns the height of this Pixa, or 0 if one was not set when it was
* created.
*
* @return the height of this Pixa, or 0 if one was not set when it was
* created
*/
public int getHeight() {
return mHeight;
}
/**
* Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width
* and height were not specified on creation.
*
* @return a bounding Rect for this Pixa
*/
public Rect getRect() {
return new Rect(0, 0, mWidth, mHeight);
}
/**
* Returns a bounding Rect for the Box at the specified index.
*
* @param index The index of the Box to get the bounding Rect of.
* @return a bounding Rect for the Box at the specified index
*/
public Rect getBoxRect(int index) {
int[] dimensions = getBoxGeometry(index);
if (dimensions == null) {
return null;
}
int x = dimensions[Box.INDEX_X];
int y = dimensions[Box.INDEX_Y];
int w = dimensions[Box.INDEX_W];
int h = dimensions[Box.INDEX_H];
Rect bound = new Rect(x, y, x + w, y + h);
return bound;
}
/**
* Returns a geometry array for the Box at the specified index. See
* Box.INDEX_* for indices.
*
* @param index The index of the Box to get the geometry of.
* @return a bounding Rect for the Box at the specified index
*/
public int[] getBoxGeometry(int index) {
int[] dimensions = new int[4];
if (getBoxGeometry(index, dimensions)) {
return dimensions;
}
return null;
}
/**
* Fills an array with the geometry of the Box at the specified index. See
* Box.INDEX_* for indices.
*
* @param index The index of the Box to get the geometry of.
* @param dimensions The array to fill with Box geometry. Must be at least 4
* elements.
* @return <code>true</code> on success
*/
public boolean getBoxGeometry(int index, int[] dimensions) {
return nativeGetBoxGeometry(mNativePixa, index, dimensions);
}
/**
* Returns an ArrayList of Box bounding Rects.
*
* @return an ArrayList of Box bounding Rects
*/
public ArrayList<Rect> getBoxRects() {
final int pixaCount = nativeGetCount(mNativePixa);
final int[] buffer = new int[4];
final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount);
for (int i = 0; i < pixaCount; i++) {
getBoxGeometry(i, buffer);
final int x = buffer[Box.INDEX_X];
final int y = buffer[Box.INDEX_Y];
final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]);
rects.add(bound);
}
return rects;
}
/**
* Replaces the Pix and Box at the specified index with the specified Pix
* and Box, both of which may be recycled after calling this method.
*
* @param index The index of the Pix to replace.
* @param pix The Pix to replace the existing Pix.
* @param box The Box to replace the existing Box.
*/
public void replacePix(int index, Pix pix, Box box) {
nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox);
}
/**
* Merges the Pix at the specified indices and removes the Pix at the second
* index.
*
* @param indexA The index of the first Pix.
* @param indexB The index of the second Pix, which will be removed after
* merging.
*/
public void mergeAndReplacePix(int indexA, int indexB) {
nativeMergeAndReplacePix(mNativePixa, indexA, indexB);
}
/**
* Writes the components of this Pix to a bitmap-formatted file using a
* random color map.
*
* @param file The file to write to.
* @return <code>true</code> on success
*/
public boolean writeToFileRandomCmap(File file) {
return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight);
}
@Override
public Iterator<Pix> iterator() {
return new PixIterator();
}
private class PixIterator implements Iterator<Pix> {
private int mIndex;
private PixIterator() {
mIndex = 0;
}
@Override
public boolean hasNext() {
final int size = size();
return (size > 0 && mIndex < size);
}
@Override
public Pix next() {
return getPix(mIndex++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeCreate(int size);
private static native int nativeCopy(int nativePixa);
private static native int nativeSort(int nativePixa, int field, int order);
private static native boolean nativeJoin(int nativePixa, int otherPixa);
private static native int nativeGetCount(int nativePixa);
private static native void nativeDestroy(int nativePixa);
private static native void nativeAddPix(int nativePixa, int nativePix, int mode);
private static native void nativeAddBox(int nativePixa, int nativeBox, int mode);
private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode);
private static native boolean nativeWriteToFileRandomCmap(
int nativePixa, String fileName, int width, int height);
private static native void nativeReplacePix(
int nativePixa, int index, int nativePix, int nativeBox);
private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB);
private static native int nativeGetBox(int nativePix, int index);
private static native int nativeGetPix(int nativePix, int index);
private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Pixa.java
|
Java
|
asf20
| 13,432
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
import android.graphics.Bitmap;
import java.io.File;
/**
* @author alanv@google.com (Alan Viverette)
*/
public class WriteFile {
static {
System.loadLibrary("lept");
}
/* Default JPEG quality */
public static final int DEFAULT_QUALITY = 85;
/* Default JPEG progressive encoding */
public static final boolean DEFAULT_PROGRESSIVE = true;
/**
* Write an 8bpp Pix to a flat byte array.
*
* @param pixs The 8bpp source image.
* @return a byte array where each byte represents a single 8-bit pixel
*/
public static byte[] writeBytes8(Pix pixs) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int size = pixs.getWidth() * pixs.getHeight();
if (pixs.getDepth() != 8) {
Pix pix8 = Convert.convertTo8(pixs);
pixs.recycle();
pixs = pix8;
}
byte[] data = new byte[size];
writeBytes8(pixs, data);
return data;
}
/**
* Write an 8bpp Pix to a flat byte array.
*
* @param pixs The 8bpp source image.
* @param data A byte array large enough to hold the pixels of pixs.
* @return the number of bytes written to data
*/
public static int writeBytes8(Pix pixs, byte[] data) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int size = pixs.getWidth() * pixs.getHeight();
if (data.length < size)
throw new IllegalArgumentException("Data array must be large enough to hold image bytes");
int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data);
return bytesWritten;
}
/**
* Writes all the images in a Pixa array to individual files using the
* specified format. The output file extension will be determined by the
* format.
* <p>
* Output file names will take the format <path>/<prefix><index>.<extension>
*
* @param pixas The source Pixa image array.
* @param path The output directory.
* @param prefix The prefix to give output files.
* @param format The format to use for output files.
* @return <code>true</code> on success
*/
public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) {
if (pixas == null)
throw new IllegalArgumentException("Source pixa must be non-null");
if (path == null)
throw new IllegalArgumentException("Destination path non-null");
if (prefix == null)
throw new IllegalArgumentException("Filename prefix must be non-null");
String rootname = new File(path, prefix).getAbsolutePath();
throw new RuntimeException("writeFiles() is not currently supported");
}
/**
* Write a Pix to a byte array using the specified encoding from
* Constants.IFF_*.
*
* @param pixs The source image.
* @param format A format from Constants.IFF_*.
* @return a byte array containing encoded bytes
*/
public static byte[] writeMem(Pix pixs, int format) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
return nativeWriteMem(pixs.mNativePix, format);
}
/**
* Writes a Pix to file using the file extension as the output format;
* supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap.
* <p>
* Uses default quality and progressive encoding settings.
*
* @param pixs Source image.
* @param file The file to write.
* @return <code>true</code> on success
*/
public static boolean writeImpliedFormat(Pix pixs, File file) {
return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE);
}
/**
* Writes a Pix to file using the file extension as the output format;
* supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap.
* <p>
* Notes:
* <ol>
* <li>This determines the output format from the filename extension.
* <li>The last two args are ignored except for requests for jpeg files.
* <li>The jpeg default quality is 75.
* </ol>
*
* @param pixs Source image.
* @param file The file to write.
* @param quality (Only for lossy formats) Quality between 1 - 100, 0 for
* default.
* @param progressive (Only for JPEG) Whether to encode as progressive.
* @return <code>true</code> on success
*/
public static boolean writeImpliedFormat(
Pix pixs, File file, int quality, boolean progressive) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (file == null)
throw new IllegalArgumentException("File must be non-null");
return nativeWriteImpliedFormat(
pixs.mNativePix, file.getAbsolutePath(), quality, progressive);
}
/**
* Writes a Pix to an Android Bitmap object. The output Bitmap will always
* be in ARGB_8888 format, but the input Pixs may be any bit-depth.
*
* @param pixs The source image.
* @return a Bitmap containing a copy of the source image, or <code>null
* </code> on failure
*/
public static Bitmap writeBitmap(Pix pixs) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
final int[] dimensions = pixs.getDimensions();
final int width = dimensions[Pix.INDEX_W];
final int height = dimensions[Pix.INDEX_H];
//final int depth = dimensions[Pix.INDEX_D];
final Bitmap.Config config = Bitmap.Config.ARGB_8888;
final Bitmap bitmap = Bitmap.createBitmap(width, height, config);
if (nativeWriteBitmap(pixs.mNativePix, bitmap)) {
return bitmap;
}
bitmap.recycle();
return null;
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeWriteBytes8(int nativePix, byte[] data);
private static native boolean nativeWriteFiles(int nativePix, String rootname, int format);
private static native byte[] nativeWriteMem(int nativePix, int format);
private static native boolean nativeWriteImpliedFormat(
int nativePix, String fileName, int quality, boolean progressive);
private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/WriteFile.java
|
Java
|
asf20
| 7,145
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Image binarization methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Binarize {
static {
System.loadLibrary("lept");
}
// Otsu thresholding constants
/** Desired tile X dimension; actual size may vary */
public final static int OTSU_SIZE_X = 32;
/** Desired tile Y dimension; actual size may vary */
public final static int OTSU_SIZE_Y = 32;
/** Desired X smoothing value */
public final static int OTSU_SMOOTH_X = 2;
/** Desired Y smoothing value */
public final static int OTSU_SMOOTH_Y = 2;
/** Fraction of the max Otsu score, typically 0.1 */
public final static float OTSU_SCORE_FRACTION = 0.1f;
/**
* Performs locally-adaptive Otsu threshold binarization with default
* parameters.
*
* @param pixs An 8 bpp PIX source image.
* @return A 1 bpp thresholded PIX image.
*/
public static Pix otsuAdaptiveThreshold(Pix pixs) {
return otsuAdaptiveThreshold(
pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION);
}
/**
* Performs locally-adaptive Otsu threshold binarization.
* <p>
* Notes:
* <ol>
* <li>The Otsu method finds a single global threshold for an image. This
* function allows a locally adapted threshold to be found for each tile
* into which the image is broken up.
* <li>The array of threshold values, one for each tile, constitutes a
* highly downscaled image. This array is optionally smoothed using a
* convolution. The full width and height of the convolution kernel are (2 *
* smoothX + 1) and (2 * smoothY + 1).
* <li>The minimum tile dimension allowed is 16. If such small tiles are
* used, it is recommended to use smoothing, because without smoothing, each
* small tile determines the splitting threshold independently. A tile that
* is entirely in the image bg will then hallucinate fg, resulting in a very
* noisy binarization. The smoothing should be large enough that no tile is
* only influenced by one type (fg or bg) of pixels, because it will force a
* split of its pixels.
* <li>To get a single global threshold for the entire image, use input
* values of sizeX and sizeY that are larger than the image. For this
* situation, the smoothing parameters are ignored.
* <li>The threshold values partition the image pixels into two classes: one
* whose values are less than the threshold and another whose values are
* greater than or equal to the threshold. This is the same use of
* 'threshold' as in pixThresholdToBinary().
* <li>The scorefract is the fraction of the maximum Otsu score, which is
* used to determine the range over which the histogram minimum is searched.
* See numaSplitDistribution() for details on the underlying method of
* choosing a threshold.
* <li>This uses enables a modified version of the Otsu criterion for
* splitting the distribution of pixels in each tile into a fg and bg part.
* The modification consists of searching for a minimum in the histogram
* over a range of pixel values where the Otsu score is within a defined
* fraction, scoreFraction, of the max score. To get the original Otsu
* algorithm, set scoreFraction == 0.
* </ol>
*
* @param pixs An 8 bpp PIX source image.
* @param sizeX Desired tile X dimension; actual size may vary.
* @param sizeY Desired tile Y dimension; actual size may vary.
* @param smoothX Half-width of convolution kernel applied to threshold
* array: use 0 for no smoothing.
* @param smoothY Half-height of convolution kernel applied to threshold
* array: use 0 for no smoothing.
* @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0
* for standard Otsu).
* @return A 1 bpp thresholded PIX image.
*/
public static Pix otsuAdaptiveThreshold(
Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (pixs.getDepth() != 8)
throw new IllegalArgumentException("Source pix depth must be 8bpp");
int nativePix = nativeOtsuAdaptiveThreshold(
pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction);
if (nativePix == 0)
throw new RuntimeException("Failed to perform Otsu adaptive threshold on image");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeOtsuAdaptiveThreshold(
int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Binarize.java
|
Java
|
asf20
| 5,515
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* @author alanv@google.com (Alan Viverette)
*/
public class Rotate {
static {
System.loadLibrary("lept");
}
// Rotation default
/** Default rotation quality is high. */
public static final boolean ROTATE_QUALITY = true;
/**
* Performs rotation using the default parameters.
*
* @param pixs The source pix.
* @param degrees The number of degrees to rotate; clockwise is positive.
* @return the rotated source image
*/
public static Pix rotate(Pix pixs, float degrees) {
return rotate(pixs, degrees, false);
}
/**
* Performs basic image rotation about the center.
* <p>
* Notes:
* <ol>
* <li>Rotation is about the center of the image.
* <li>For very small rotations, just return a clone.
* <li>Rotation brings either white or black pixels in from outside the
* image.
* <li>Above 20 degrees, if rotation by shear is requested, we rotate by
* sampling.
* <li>Colormaps are removed for rotation by area map and shear.
* <li>The dest can be expanded so that no image pixels are lost. To invoke
* expansion, input the original width and height. For repeated rotation,
* use of the original width and height allows the expansion to stop at the
* maximum required size, which is a square with side = sqrt(w*w + h*h).
* </ol>
*
* @param pixs The source pix.
* @param degrees The number of degrees to rotate; clockwise is positive.
* @param quality Whether to use high-quality rotation.
* @return the rotated source image
*/
public static Pix rotate(Pix pixs, float degrees, boolean quality) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeRotate(pixs.mNativePix, degrees, quality);
if (nativePix == 0)
return null;
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeRotate(int nativePix, float degrees, boolean quality);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Rotate.java
|
Java
|
asf20
| 2,768
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Image rotation and skew detection methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Skew {
static {
System.loadLibrary("lept");
}
// Text alignment defaults
/** Default range for sweep, will detect rotation of + or - 30 degrees. */
public final static float SWEEP_RANGE = 30.0f;
/** Default sweep delta, reasonably accurate within 0.05 degrees. */
public final static float SWEEP_DELTA = 5.0f;
/** Default sweep reduction, one-eighth the size of the original image. */
public final static int SWEEP_REDUCTION = 8;
/** Default sweep reduction, one-fourth the size of the original image. */
public final static int SEARCH_REDUCTION = 4;
/** Default search minimum delta, reasonably accurate within 0.05 degrees. */
public final static float SEARCH_MIN_DELTA = 0.01f;
/**
* Finds and returns the skew angle using default parameters.
*
* @param pixs Input pix (1 bpp).
* @return the detected skew angle, or 0.0 on failure
*/
public static float findSkew(Pix pixs) {
return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION,
SEARCH_MIN_DELTA);
}
/**
* Finds and returns the skew angle, doing first a sweep through a set of
* equal angles, and then doing a binary search until convergence.
* <p>
* Notes:
* <ol>
* <li>In computing the differential line sum variance score, we sum the
* result over scanlines, but we always skip:
* <ul>
* <li>at least one scanline
* <li>not more than 10% of the image height
* <li>not more than 5% of the image width
* </ul>
* </ol>
*
* @param pixs Input pix (1 bpp).
* @param sweepRange Half the full search range, assumed about 0; in
* degrees.
* @param sweepDelta Angle increment of sweep; in degrees.
* @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8.
* @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and
* must not exceed redsweep.
* @param searchMinDelta Minimum binary search increment angle; in degrees.
* @return the detected skew angle, or 0.0 on failure
*/
public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction,
int searchReduction, float searchMinDelta) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction,
searchReduction, searchMinDelta);
}
// ***************
// * NATIVE CODE *
// ***************
private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta,
int sweepReduction, int searchReduction, float searchMinDelta);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Skew.java
|
Java
|
asf20
| 3,562
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Image adaptive mapping methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class AdaptiveMap {
static {
System.loadLibrary("lept");
}
// Background normalization constants
/** Image reduction value; possible values are 1, 2, 4, 8 */
private final static int NORM_REDUCTION = 16;
/** Desired tile size; actual size may vary */
private final static int NORM_SIZE = 3;
/** Background brightness value; values over 200 may result in clipping */
private final static int NORM_BG_VALUE = 200;
/**
* Normalizes an image's background using default parameters.
*
* @param pixs A source pix image.
* @return the source pix image with a normalized background
*/
public static Pix backgroundNormMorph(Pix pixs) {
return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE);
}
/**
* Normalizes an image's background to a specified value.
* <p>
* Notes:
* <ol>
* <li>This is a top-level interface for normalizing the image intensity by
* mapping the image so that the background is near the input value 'bgval'.
* <li>The input image is either grayscale or rgb.
* <li>For each component in the input image, the background value is
* estimated using a grayscale closing; hence the 'Morph' in the function
* name.
* <li>An optional binary mask can be specified, with the foreground pixels
* typically over image regions. The resulting background map values will be
* determined by surrounding pixels that are not under the mask foreground.
* The origin (0,0) of this mask is assumed to be aligned with the origin of
* the input image. This binary mask must not fully cover pixs, because then
* there will be no pixels in the input image available to compute the
* background.
* <li>The map is computed at reduced size (given by 'reduction') from the
* input pixs and optional pixim. At this scale, pixs is closed to remove
* the background, using a square Sel of odd dimension. The product of
* reduction * size should be large enough to remove most of the text
* foreground.
* <li>No convolutional smoothing needs to be done on the map before
* inverting it.
* <li>A 'bgval' target background value for the normalized image. This
* should be at least 128. If set too close to 255, some clipping will occur
* in the result.
* </ol>
*
* @param pixs A source pix image.
* @param normReduction Reduction at which morphological closings are done.
* @param normSize Size of square Sel for the closing.
* @param normBgValue Target background value.
* @return the source pix image with a normalized background
*/
public static Pix backgroundNormMorph(
Pix pixs, int normReduction, int normSize, int normBgValue) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeBackgroundNormMorph(
pixs.mNativePix, normReduction, normSize, normBgValue);
if (nativePix == 0)
throw new RuntimeException("Failed to normalize image background");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeBackgroundNormMorph(
int nativePix, int reduction, int size, int bgval);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/AdaptiveMap.java
|
Java
|
asf20
| 4,135
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Image sharpening methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Enhance {
static {
System.loadLibrary("lept");
}
/**
* Performs unsharp masking (edge enhancement).
* <p>
* Notes:
* <ul>
* <li>We use symmetric smoothing filters of odd dimension, typically use
* sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is
* (size - 1)/2; i.e., 1, 2, 3, etc.</li>
* <li>The <code>fract</code> parameter is typically taken in the range: 0.2
* < <code>fract</code> < 0.7</li>
* </ul>
*
* @param halfwidth The half-width of the smoothing filter.
* @param fraction The fraction of edge to be added back into the source
* image.
* @return an edge-enhanced Pix image or copy if no enhancement requested
*/
public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Enhance.java
|
Java
|
asf20
| 2,068
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* JPEG input and output methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class JpegIO {
static {
System.loadLibrary("lept");
}
/** Default quality is 85%, which is reasonably good. */
public static final int DEFAULT_QUALITY = 85;
/** Progressive encoding is disabled by default to increase compatibility. */
public static final boolean DEFAULT_PROGRESSIVE = false;
/**
* Returns a compressed JPEG byte representation of this Pix using default
* parameters.
*
* @param pixs
* @return a compressed JPEG byte array representation of the Pix
*/
public static byte[] compressToJpeg(Pix pixs) {
return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE);
}
/**
* Returns a compressed JPEG byte representation of this Pix.
*
* @param pixs A source pix image.
* @param quality The quality of the compressed image. Valid range is 0-100.
* @param progressive Whether to use progressive compression.
* @return a compressed JPEG byte array representation of the Pix
*/
public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (quality < 0 || quality > 100)
throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)");
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
final Bitmap bmp = WriteFile.writeBitmap(pixs);
bmp.compress(CompressFormat.JPEG, quality, byteStream);
bmp.recycle();
final byte[] encodedData = byteStream.toByteArray();
try {
byteStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return encodedData;
}
// ***************
// * NATIVE CODE *
// ***************
private static native byte[] nativeCompressToJpeg(
int nativePix, int quality, boolean progressive);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/JpegIO.java
|
Java
|
asf20
| 2,862
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Leptonica constants.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Constants {
/*-------------------------------------------------------------------------*
* Access and storage flags *
*-------------------------------------------------------------------------*/
/*
* For Pix, Box, Pta and Numa, there are 3 standard methods for handling the
* retrieval or insertion of a struct: (1) direct insertion (Don't do this
* if there is another handle somewhere to this same struct!) (2) copy
* (Always safe, sets up a refcount of 1 on the new object. Can be
* undesirable if very large, such as an image or an array of images.) (3)
* clone (Makes another handle to the same struct, and bumps the refcount up
* by 1. Safe to do unless you're changing data through one of the handles
* but don't want those changes to be seen by the other handle.) For Pixa
* and Boxa, which are structs that hold an array of clonable structs, there
* is an additional method: (4) copy-clone (Makes a new higher-level struct
* with a refcount of 1, but clones all the structs in the array.) Unlike
* the other structs, when retrieving a string from an Sarray, you are
* allowed to get a handle without a copy or clone (i.e., that you don't
* own!). You must not free or insert such a string! Specifically, for an
* Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or
* FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or
* 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1,
* and L_INSERT and L_NOCOPY are always 0.
*/
/* Stuff it in; no copy, clone or copy-clone */
public static final int L_INSERT = 0;
/* Make/use a copy of the object */
public static final int L_COPY = 1;
/* Make/use clone (ref count) of the object */
public static final int L_CLONE = 2;
/*
* Make a new object and fill with with clones of each object in the
* array(s)
*/
public static final int L_COPY_CLONE = 3;
/*--------------------------------------------------------------------------*
* Sort flags *
*--------------------------------------------------------------------------*/
/* Sort in increasing order */
public static final int L_SORT_INCREASING = 1;
/* Sort in decreasing order */
public static final int L_SORT_DECREASING = 2;
/* Sort box or c.c. by horiz location */
public static final int L_SORT_BY_X = 3;
/* Sort box or c.c. by vert location */
public static final int L_SORT_BY_Y = 4;
/* Sort box or c.c. by width */
public static final int L_SORT_BY_WIDTH = 5;
/* Sort box or c.c. by height */
public static final int L_SORT_BY_HEIGHT = 6;
/* Sort box or c.c. by min dimension */
public static final int L_SORT_BY_MIN_DIMENSION = 7;
/* Sort box or c.c. by max dimension */
public static final int L_SORT_BY_MAX_DIMENSION = 8;
/* Sort box or c.c. by perimeter */
public static final int L_SORT_BY_PERIMETER = 9;
/* Sort box or c.c. by area */
public static final int L_SORT_BY_AREA = 10;
/* Sort box or c.c. by width/height ratio */
public static final int L_SORT_BY_ASPECT_RATIO = 11;
/* ------------------ Image file format types -------------- */
/*
* The IFF_DEFAULT flag is used to write the file out in the same (input)
* file format that the pix was read from. If the pix was not read from
* file, the input format field will be IFF_UNKNOWN and the output file
* format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4
* for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which
* is not supported in leptonica.
*/
public static final int IFF_UNKNOWN = 0;
public static final int IFF_BMP = 1;
public static final int IFF_JFIF_JPEG = 2;
public static final int IFF_PNG = 3;
public static final int IFF_TIFF = 4;
public static final int IFF_TIFF_PACKBITS = 5;
public static final int IFF_TIFF_RLE = 6;
public static final int IFF_TIFF_G3 = 7;
public static final int IFF_TIFF_G4 = 8;
public static final int IFF_TIFF_LZW = 9;
public static final int IFF_TIFF_ZIP = 10;
public static final int IFF_PNM = 11;
public static final int IFF_PS = 12;
public static final int IFF_GIF = 13;
public static final int IFF_JP2 = 14;
public static final int IFF_DEFAULT = 15;
public static final int IFF_SPIX = 16;
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Constants.java
|
Java
|
asf20
| 5,352
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.leptonica.android;
/**
* Image scaling methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Scale {
static {
System.loadLibrary("lept");
}
public enum ScaleType {
/* Scale in X and Y independently, so that src matches dst exactly. */
FILL,
/*
* Compute a scale that will maintain the original src aspect ratio, but
* will also ensure that src fits entirely inside dst. May shrink or
* expand src to fit dst.
*/
FIT,
/*
* Compute a scale that will maintain the original src aspect ratio, but
* will also ensure that src fits entirely inside dst. May shrink src to
* fit dst, but will not expand it.
*/
FIT_SHRINK,
}
/**
* Scales the Pix to a specified width and height using a specified scaling
* type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix
* if no scaling is required.
*
* @param pixs
* @param width
* @param height
* @param type
* @return a scaled image or a clone of the Pix if no scaling is required
*/
public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int pixWidth = pixs.getWidth();
int pixHeight = pixs.getHeight();
float scaleX = width / (float) pixWidth;
float scaleY = height / (float) pixHeight;
switch (type) {
case FILL:
// Retains default scaleX and scaleY values
break;
case FIT:
scaleX = Math.min(scaleX, scaleY);
scaleY = scaleX;
break;
case FIT_SHRINK:
scaleX = Math.min(1.0f, Math.min(scaleX, scaleY));
scaleY = scaleX;
break;
}
return scale(pixs, scaleX, scaleY);
}
/**
* Scales the Pix to specified scale. If no scaling is required, returns a
* clone of the source Pix.
*
* @param pixs the source Pix
* @param scale dimension scaling factor
* @return a Pix scaled according to the supplied factors
*/
public static Pix scale(Pix pixs, float scale) {
return scale(pixs, scale, scale);
}
/**
* Scales the Pix to specified x and y scale. If no scaling is required,
* returns a clone of the source Pix.
*
* @param pixs the source Pix
* @param scaleX x-dimension (width) scaling factor
* @param scaleY y-dimension (height) scaling factor
* @return a Pix scaled according to the supplied factors
*/
public static Pix scale(Pix pixs, float scaleX, float scaleY) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (scaleX <= 0.0f)
throw new IllegalArgumentException("X scaling factor must be positive");
if (scaleY <= 0.0f)
throw new IllegalArgumentException("Y scaling factor must be positive");
int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY);
if (nativePix == 0)
throw new RuntimeException("Failed to natively scale pix");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeScale(int nativePix, float scaleX, float scaleY);
}
|
1006373c-hello
|
tesseract-android-tools/src/com/googlecode/leptonica/android/Scale.java
|
Java
|
asf20
| 4,131
|
/*
* Copyright 2010, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TESSERACT_JNI_COMMON_H
#define TESSERACT_JNI_COMMON_H
#include <jni.h>
#include <android/log.h>
#include <assert.h>
#define LOG_TAG "Tesseract(native)"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__)
#endif
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_tesseract_android/common.h
|
C
|
asf20
| 1,263
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <malloc.h>
#include "android/bitmap.h"
#include "common.h"
#include "baseapi.h"
#include "allheaders.h"
static jfieldID field_mNativeData;
struct native_data_t {
tesseract::TessBaseAPI api;
PIX *pix;
void *data;
bool debug;
native_data_t() {
pix = NULL;
data = NULL;
debug = false;
}
};
static inline native_data_t * get_native_data(JNIEnv *env, jobject object) {
return (native_data_t *) (env->GetIntField(object, field_mNativeData));
}
#ifdef __cplusplus
extern "C" {
#endif
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv *env;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) {
LOGE("Failed to get the environment using GetEnv()");
return -1;
}
return JNI_VERSION_1_6;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClassInit(JNIEnv* env, jclass clazz) {
field_mNativeData = env->GetFieldID(clazz, "mNativeData", "I");
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeConstruct(JNIEnv* env, jobject object) {
native_data_t *nat = new native_data_t;
if (nat == NULL) {
LOGE("%s: out of memory!", __FUNCTION__);
return;
}
env->SetIntField(object, field_mNativeData, (jint) nat);
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeFinalize(JNIEnv* env, jobject object) {
native_data_t *nat = get_native_data(env, object);
// Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native
// code struct. We need to free that pointer when we release our instance of Tesseract or
// attempt to set a new image using one of the nativeSet* methods.
if (nat->data != NULL)
free(nat->data);
else if (nat->pix != NULL)
pixDestroy(&nat->pix);
nat->data = NULL;
nat->pix = NULL;
if (nat != NULL)
delete nat;
}
jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInit(JNIEnv *env, jobject thiz,
jstring dir, jstring lang) {
native_data_t *nat = get_native_data(env, thiz);
const char *c_dir = env->GetStringUTFChars(dir, NULL);
const char *c_lang = env->GetStringUTFChars(lang, NULL);
jboolean res = JNI_TRUE;
if (nat->api.Init(c_dir, c_lang)) {
LOGE("Could not initialize Tesseract API with language=%s!", c_lang);
res = JNI_FALSE;
} else {
LOGI("Initialized Tesseract API with language=%s", c_lang);
}
env->ReleaseStringUTFChars(lang, c_dir);
env->ReleaseStringUTFChars(lang, c_lang);
return res;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImageBytes(JNIEnv *env,
jobject thiz,
jbyteArray data,
jint width, jint height,
jint bpp, jint bpl) {
jbyte *data_array = env->GetByteArrayElements(data, NULL);
int count = env->GetArrayLength(data);
unsigned char* imagedata = (unsigned char *) malloc(count * sizeof(unsigned char));
// This is painfully slow, but necessary because we don't know
// how many bits the JVM might be using to represent a byte
for (int i = 0; i < count; i++) {
imagedata[i] = (unsigned char) data_array[i];
}
env->ReleaseByteArrayElements(data, data_array, JNI_ABORT);
native_data_t *nat = get_native_data(env, thiz);
nat->api.SetImage(imagedata, (int) width, (int) height, (int) bpp, (int) bpl);
// Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native
// code struct. We need to free that pointer when we release our instance of Tesseract or
// attempt to set a new image using one of the nativeSet* methods.
if (nat->data != NULL)
free(nat->data);
else if (nat->pix != NULL)
pixDestroy(&nat->pix);
nat->data = imagedata;
nat->pix = NULL;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImagePix(JNIEnv *env, jobject thiz,
jint nativePix) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixClone(pixs);
native_data_t *nat = get_native_data(env, thiz);
nat->api.SetImage(pixd);
// Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native
// code struct. We need to free that pointer when we release our instance of Tesseract or
// attempt to set a new image using one of the nativeSet* methods.
if (nat->data != NULL)
free(nat->data);
else if (nat->pix != NULL)
pixDestroy(&nat->pix);
nat->data = NULL;
nat->pix = pixd;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetRectangle(JNIEnv *env,
jobject thiz, jint left,
jint top, jint width,
jint height) {
native_data_t *nat = get_native_data(env, thiz);
nat->api.SetRectangle(left, top, width, height);
}
jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetUTF8Text(JNIEnv *env,
jobject thiz) {
native_data_t *nat = get_native_data(env, thiz);
char *text = nat->api.GetUTF8Text();
jstring result = env->NewStringUTF(text);
free(text);
return result;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeStop(JNIEnv *env, jobject thiz) {
native_data_t *nat = get_native_data(env, thiz);
// TODO How do we stop without a monitor?!
}
jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeMeanConfidence(JNIEnv *env,
jobject thiz) {
native_data_t *nat = get_native_data(env, thiz);
return (jint) nat->api.MeanTextConf();
}
jintArray Java_com_googlecode_tesseract_android_TessBaseAPI_nativeWordConfidences(JNIEnv *env,
jobject thiz) {
native_data_t *nat = get_native_data(env, thiz);
int *confs = nat->api.AllWordConfidences();
if (confs == NULL) {
return NULL;
}
int len, *trav;
for (len = 0, trav = confs; *trav != -1; trav++, len++)
;
LOG_ASSERT((confs != NULL), "Confidence array has %d elements", len);
jintArray ret = env->NewIntArray(len);
LOG_ASSERT((ret != NULL), "Could not create Java confidence array!");
env->SetIntArrayRegion(ret, 0, len, confs);
delete[] confs;
return ret;
}
jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetVariable(JNIEnv *env,
jobject thiz,
jstring var,
jstring value) {
native_data_t *nat = get_native_data(env, thiz);
const char *c_var = env->GetStringUTFChars(var, NULL);
const char *c_value = env->GetStringUTFChars(value, NULL);
jboolean set = nat->api.SetVariable(c_var, c_value) ? JNI_TRUE : JNI_FALSE;
env->ReleaseStringUTFChars(var, c_var);
env->ReleaseStringUTFChars(value, c_value);
return set;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClear(JNIEnv *env, jobject thiz) {
native_data_t *nat = get_native_data(env, thiz);
nat->api.Clear();
// Call between pages or documents etc to free up memory and forget adaptive data.
nat->api.ClearAdaptiveClassifier();
// Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native
// code struct. We need to free that pointer when we release our instance of Tesseract or
// attempt to set a new image using one of the nativeSet* methods.
if (nat->data != NULL)
free(nat->data);
else if (nat->pix != NULL)
pixDestroy(&nat->pix);
nat->data = NULL;
nat->pix = NULL;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeEnd(JNIEnv *env, jobject thiz) {
native_data_t *nat = get_native_data(env, thiz);
nat->api.End();
// Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native
// code struct. We need to free that pointer when we release our instance of Tesseract or
// attempt to set a new image using one of the nativeSet* methods.
if (nat->data != NULL)
free(nat->data);
else if (nat->pix != NULL)
pixDestroy(&nat->pix);
nat->data = NULL;
nat->pix = NULL;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetDebug(JNIEnv *env, jobject thiz,
jboolean debug) {
native_data_t *nat = get_native_data(env, thiz);
nat->debug = (debug == JNI_TRUE) ? TRUE : FALSE;
}
void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetPageSegMode(JNIEnv *env,
jobject thiz, jint mode) {
native_data_t *nat = get_native_data(env, thiz);
nat->api.SetPageSegMode((tesseract::PageSegMode) mode);
}
#ifdef __cplusplus
}
#endif
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_tesseract_android/tessbaseapi.cpp
|
C++
|
asf20
| 9,909
|
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := libtess
# tesseract (minus executable)
BLACKLIST_SRC_FILES := \
%api/tesseractmain.cpp \
%viewer/svpaint.cpp
TESSERACT_SRC_FILES := \
$(wildcard $(TESSERACT_PATH)/api/*.cpp) \
$(wildcard $(TESSERACT_PATH)/ccmain/*.cpp) \
$(wildcard $(TESSERACT_PATH)/ccstruct/*.cpp) \
$(wildcard $(TESSERACT_PATH)/ccutil/*.cpp) \
$(wildcard $(TESSERACT_PATH)/classify/*.cpp) \
$(wildcard $(TESSERACT_PATH)/cube/*.cpp) \
$(wildcard $(TESSERACT_PATH)/cutil/*.cpp) \
$(wildcard $(TESSERACT_PATH)/dict/*.cpp) \
$(wildcard $(TESSERACT_PATH)/image/*.cpp) \
$(wildcard $(TESSERACT_PATH)/neural_networks/runtime/*.cpp) \
$(wildcard $(TESSERACT_PATH)/textord/*.cpp) \
$(wildcard $(TESSERACT_PATH)/viewer/*.cpp) \
$(wildcard $(TESSERACT_PATH)/wordrec/*.cpp)
LOCAL_SRC_FILES := \
$(filter-out $(BLACKLIST_SRC_FILES),$(subst $(LOCAL_PATH)/,,$(TESSERACT_SRC_FILES)))
LOCAL_C_INCLUDES := \
$(TESSERACT_PATH)/api \
$(TESSERACT_PATH)/ccmain \
$(TESSERACT_PATH)/ccstruct \
$(TESSERACT_PATH)/ccutil \
$(TESSERACT_PATH)/classify \
$(TESSERACT_PATH)/cube \
$(TESSERACT_PATH)/cutil \
$(TESSERACT_PATH)/dict \
$(TESSERACT_PATH)/image \
$(TESSERACT_PATH)/neural_networks/runtime \
$(TESSERACT_PATH)/textord \
$(TESSERACT_PATH)/viewer \
$(TESSERACT_PATH)/wordrec \
$(LEPTONICA_PATH)/src
LOCAL_CFLAGS := \
-DHAVE_LIBLEPT \
-DUSE_STD_NAMESPACE \
-D'VERSION="Android"' \
-include ctype.h \
-include unistd.h \
# jni
LOCAL_SRC_FILES += \
tessbaseapi.cpp
LOCAL_C_INCLUDES += \
$(LOCAL_PATH)
LOCAL_LDLIBS += \
-ljnigraphics \
-llog
# common
LOCAL_PRELINK_MODULE := false
LOCAL_SHARED_LIBRARIES := liblept
include $(BUILD_SHARED_LIBRARY)
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_tesseract_android/Android.mk
|
Makefile
|
asf20
| 1,750
|
/* Copyright (C) 2007 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*
* Modifications for Android written Jul 2009 by Alan Viverette
*/
/*
FUNCTION
<<fmemopen>>---open a stream around a fixed-length string
INDEX
fmemopen
ANSI_SYNOPSIS
#include <stdio.h>
FILE *fmemopen(void *restrict <[buf]>, size_t <[size]>,
const char *restrict <[mode]>);
DESCRIPTION
<<fmemopen>> creates a seekable <<FILE>> stream that wraps a
fixed-length buffer of <[size]> bytes starting at <[buf]>. The stream
is opened with <[mode]> treated as in <<fopen>>, where append mode
starts writing at the first NUL byte. If <[buf]> is NULL, then
<[size]> bytes are automatically provided as if by <<malloc>>, with
the initial size of 0, and <[mode]> must contain <<+>> so that data
can be read after it is written.
The stream maintains a current position, which moves according to
bytes read or written, and which can be one past the end of the array.
The stream also maintains a current file size, which is never greater
than <[size]>. If <[mode]> starts with <<r>>, the position starts at
<<0>>, and file size starts at <[size]> if <[buf]> was provided. If
<[mode]> starts with <<w>>, the position and file size start at <<0>>,
and if <[buf]> was provided, the first byte is set to NUL. If
<[mode]> starts with <<a>>, the position and file size start at the
location of the first NUL byte, or else <[size]> if <[buf]> was
provided.
When reading, NUL bytes have no significance, and reads cannot exceed
the current file size. When writing, the file size can increase up to
<[size]> as needed, and NUL bytes may be embedded in the stream (see
<<open_memstream>> for an alternative that automatically enlarges the
buffer). When the stream is flushed or closed after a write that
changed the file size, a NUL byte is written at the current position
if there is still room; if the stream is not also open for reading, a
NUL byte is additionally written at the last byte of <[buf]> when the
stream has exceeded <[size]>, so that a write-only <[buf]> is always
NUL-terminated when the stream is flushed or closed (and the initial
<[size]> should take this into account). It is not possible to seek
outside the bounds of <[size]>. A NUL byte written during a flush is
restored to its previous value when seeking elsewhere in the string.
RETURNS
The return value is an open FILE pointer on success. On error,
<<NULL>> is returned, and <<errno>> will be set to EINVAL if <[size]>
is zero or <[mode]> is invalid, ENOMEM if <[buf]> was NULL and memory
could not be allocated, or EMFILE if too many streams are already
open.
PORTABILITY
This function is being added to POSIX 200x, but is not in POSIX 2001.
Supporting OS subroutines required: <<sbrk>>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <malloc.h>
#include "extrastdio.h"
/* Describe details of an open memstream. */
typedef struct fmemcookie {
void *storage; /* storage to free on close */
char *buf; /* buffer start */
size_t pos; /* current position */
size_t eof; /* current file size */
size_t max; /* maximum file size */
char append; /* nonzero if appending */
char writeonly; /* 1 if write-only */
char saved; /* saved character that lived at pos before write-only NUL */
} fmemcookie;
/* Read up to non-zero N bytes into BUF from stream described by
COOKIE; return number of bytes read (0 on EOF). */
static int
fmemread(void *cookie, char *buf, int n)
{
fmemcookie *c = (fmemcookie *) cookie;
/* Can't read beyond current size, but EOF condition is not an error. */
if (c->pos > c->eof)
return 0;
if (n >= c->eof - c->pos)
n = c->eof - c->pos;
memcpy (buf, c->buf + c->pos, n);
c->pos += n;
return n;
}
/* Write up to non-zero N bytes of BUF into the stream described by COOKIE,
returning the number of bytes written or EOF on failure. */
static int
fmemwrite(void *cookie, const char *buf, int n)
{
fmemcookie *c = (fmemcookie *) cookie;
int adjust = 0; /* true if at EOF, but still need to write NUL. */
/* Append always seeks to eof; otherwise, if we have previously done
a seek beyond eof, ensure all intermediate bytes are NUL. */
if (c->append)
c->pos = c->eof;
else if (c->pos > c->eof)
memset (c->buf + c->eof, '\0', c->pos - c->eof);
/* Do not write beyond EOF; saving room for NUL on write-only stream. */
if (c->pos + n > c->max - c->writeonly)
{
adjust = c->writeonly;
n = c->max - c->pos;
}
/* Now n is the number of bytes being modified, and adjust is 1 if
the last byte is NUL instead of from buf. Write a NUL if
write-only; or if read-write, eof changed, and there is still
room. When we are within the file contents, remember what we
overwrite so we can restore it if we seek elsewhere later. */
if (c->pos + n > c->eof)
{
c->eof = c->pos + n;
if (c->eof - adjust < c->max)
c->saved = c->buf[c->eof - adjust] = '\0';
}
else if (c->writeonly)
{
if (n)
{
c->saved = c->buf[c->pos + n - adjust];
c->buf[c->pos + n - adjust] = '\0';
}
else
adjust = 0;
}
c->pos += n;
if (n - adjust)
memcpy (c->buf + c->pos - n, buf, n - adjust);
else
{
return EOF;
}
return n;
}
/* Seek to position POS relative to WHENCE within stream described by
COOKIE; return resulting position or fail with EOF. */
static fpos_t
fmemseek(void *cookie, fpos_t pos, int whence)
{
fmemcookie *c = (fmemcookie *) cookie;
off_t offset = (off_t) pos;
if (whence == SEEK_CUR)
offset += c->pos;
else if (whence == SEEK_END)
offset += c->eof;
if (offset < 0)
{
offset = -1;
}
else if (offset > c->max)
{
offset = -1;
}
else
{
if (c->writeonly && c->pos < c->eof)
{
c->buf[c->pos] = c->saved;
c->saved = '\0';
}
c->pos = offset;
if (c->writeonly && c->pos < c->eof)
{
c->saved = c->buf[c->pos];
c->buf[c->pos] = '\0';
}
}
return (fpos_t) offset;
}
/* Reclaim resources used by stream described by COOKIE. */
static int
fmemclose(void *cookie)
{
fmemcookie *c = (fmemcookie *) cookie;
free (c->storage);
return 0;
}
/* Open a memstream around buffer BUF of SIZE bytes, using MODE.
Return the new stream, or fail with NULL. */
FILE *
fmemopen(void *buf, size_t size, const char *mode)
{
FILE *fp;
fmemcookie *c;
int flags;
int dummy;
if ((flags = __sflags (mode, &dummy)) == 0)
return NULL;
if (!size || !(buf || flags & __SAPP))
{
return NULL;
}
if ((fp = (FILE *) __sfp ()) == NULL)
return NULL;
if ((c = (fmemcookie *) malloc (sizeof *c + (buf ? 0 : size))) == NULL)
{
fp->_flags = 0; /* release */
return NULL;
}
c->storage = c;
c->max = size;
/* 9 modes to worry about. */
/* w/a, buf or no buf: Guarantee a NUL after any file writes. */
c->writeonly = (flags & __SWR) != 0;
c->saved = '\0';
if (!buf)
{
/* r+/w+/a+, and no buf: file starts empty. */
c->buf = (char *) (c + 1);
*(char *) buf = '\0';
c->pos = c->eof = 0;
c->append = (flags & __SAPP) != 0;
}
else
{
c->buf = (char *) buf;
switch (*mode)
{
case 'a':
/* a/a+ and buf: position and size at first NUL. */
buf = memchr (c->buf, '\0', size);
c->eof = c->pos = buf ? (char *) buf - c->buf : size;
if (!buf && c->writeonly)
/* a: guarantee a NUL within size even if no writes. */
c->buf[size - 1] = '\0';
c->append = 1;
break;
case 'r':
/* r/r+ and buf: read at beginning, full size available. */
c->pos = c->append = 0;
c->eof = size;
break;
case 'w':
/* w/w+ and buf: write at beginning, truncate to empty. */
c->pos = c->append = c->eof = 0;
*c->buf = '\0';
break;
default:
abort();
}
}
fp->_file = -1;
fp->_flags = flags;
fp->_cookie = c;
fp->_read = flags & (__SRD | __SRW) ? fmemread : NULL;
fp->_write = flags & (__SWR | __SRW) ? fmemwrite : NULL;
fp->_seek = fmemseek;
fp->_close = fmemclose;
return fp;
}
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/stdio/fmemopen.c
|
C
|
asf20
| 8,195
|
/* Copyright (C) 2007 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*
* Modifications for Android written Jul 2009 by Alan Viverette
*/
/*
FUNCTION
<<open_memstream>>---open a write stream around an arbitrary-length string
INDEX
open_memstream
ANSI_SYNOPSIS
#include <stdio.h>
FILE *open_memstream(char **restrict <[buf]>,
size_t *restrict <[size]>);
DESCRIPTION
<<open_memstream>> creates a seekable <<FILE>> stream that wraps an
arbitrary-length buffer, created as if by <<malloc>>. The current
contents of *<[buf]> are ignored; this implementation uses *<[size]>
as a hint of the maximum size expected, but does not fail if the hint
was wrong. The parameters <[buf]> and <[size]> are later stored
through following any call to <<fflush>> or <<fclose>>, set to the
current address and usable size of the allocated string; although
after fflush, the pointer is only valid until another stream operation
that results in a write. Behavior is undefined if the user alters
either *<[buf]> or *<[size]> prior to <<fclose>>.
The stream is write-only, since the user can directly read *<[buf]>
after a flush; see <<fmemopen>> for a way to wrap a string with a
readable stream. The user is responsible for calling <<free>> on
the final *<[buf]> after <<fclose>>.
Any time the stream is flushed, a NUL byte is written at the current
position (but is not counted in the buffer length), so that the string
is always NUL-terminated after at most *<[size]> bytes. However, data
previously written beyond the current stream offset is not lost, and
the NUL byte written during a flush is restored to its previous value
when seeking elsewhere in the string.
RETURNS
The return value is an open FILE pointer on success. On error,
<<NULL>> is returned, and <<errno>> will be set to EINVAL if <[buf]>
or <[size]> is NULL, ENOMEM if memory could not be allocated, or
EMFILE if too many streams are already open.
PORTABILITY
This function is being added to POSIX 200x, but is not in POSIX 2001.
Supporting OS subroutines required: <<sbrk>>.
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <malloc.h>
#include "extrastdio.h"
/* Describe details of an open memstream. */
typedef struct memstream {
void *storage; /* storage to free on close */
char **pbuf; /* pointer to the current buffer */
size_t *psize; /* pointer to the current size, smaller of pos or eof */
size_t pos; /* current position */
size_t eof; /* current file size */
size_t max; /* current malloc buffer size, always > eof */
char saved; /* saved character that lived at *psize before NUL */
} memstream;
/* Write up to non-zero N bytes of BUF into the stream described by COOKIE,
returning the number of bytes written or EOF on failure. */
static int
memwrite(void *cookie, const char *buf, int n)
{
memstream *c = (memstream *) cookie;
char *cbuf = *c->pbuf;
/* size_t is unsigned, but off_t is signed. Don't let stream get so
big that user cannot do ftello. */
if (sizeof (off_t) == sizeof (size_t) && (ssize_t) (c->pos + n) < 0)
{
return EOF;
}
/* Grow the buffer, if necessary. Choose a geometric growth factor
to avoid quadratic realloc behavior, but use a rate less than
(1+sqrt(5))/2 to accomodate malloc overhead. Overallocate, so
that we can add a trailing \0 without reallocating. The new
allocation should thus be max(prev_size*1.5, c->pos+n+1). */
if (c->pos + n >= c->max)
{
size_t newsize = c->max * 3 / 2;
if (newsize < c->pos + n + 1)
newsize = c->pos + n + 1;
cbuf = realloc (cbuf, newsize);
if (! cbuf)
return EOF; /* errno already set to ENOMEM */
*c->pbuf = cbuf;
c->max = newsize;
}
/* If we have previously done a seek beyond eof, ensure all
intermediate bytes are NUL. */
if (c->pos > c->eof)
memset (cbuf + c->eof, '\0', c->pos - c->eof);
memcpy (cbuf + c->pos, buf, n);
c->pos += n;
/* If the user has previously written further, remember what the
trailing NUL is overwriting. Otherwise, extend the stream. */
if (c->pos > c->eof)
c->eof = c->pos;
else
c->saved = cbuf[c->pos];
cbuf[c->pos] = '\0';
*c->psize = c->pos;
return n;
}
/* Seek to position POS relative to WHENCE within stream described by
COOKIE; return resulting position or fail with EOF. */
static fpos_t
memseek(void *cookie, fpos_t pos, int whence)
{
memstream *c = (memstream *) cookie;
off_t offset = (off_t) pos;
if (whence == SEEK_CUR)
offset += c->pos;
else if (whence == SEEK_END)
offset += c->eof;
if (offset < 0)
{
offset = -1;
}
else if ((size_t) offset != offset)
{
offset = -1;
}
else
{
if (c->pos < c->eof)
{
(*c->pbuf)[c->pos] = c->saved;
c->saved = '\0';
}
c->pos = offset;
if (c->pos < c->eof)
{
c->saved = (*c->pbuf)[c->pos];
(*c->pbuf)[c->pos] = '\0';
*c->psize = c->pos;
}
else
*c->psize = c->eof;
}
return (fpos_t) offset;
}
/* Reclaim resources used by stream described by COOKIE. */
static int
memclose(void *cookie)
{
memstream *c = (memstream *) cookie;
char *buf;
/* Be nice and try to reduce any unused memory. */
buf = realloc (*c->pbuf, *c->psize + 1);
if (buf)
*c->pbuf = buf;
free (c->storage);
return 0;
}
/* Open a memstream that tracks a dynamic buffer in BUF and SIZE.
Return the new stream, or fail with NULL. */
FILE *
open_memstream(char **buf, size_t *size)
{
FILE *fp;
memstream *c;
int flags;
if (!buf || !size)
{
return NULL;
}
if ((fp = (FILE *) __sfp ()) == NULL)
return NULL;
if ((c = (memstream *) malloc (sizeof *c)) == NULL)
{
fp->_flags = 0; /* release */
return NULL;
}
/* Use *size as a hint for initial sizing, but bound the initial
malloc between 64 bytes (same as asprintf, to avoid frequent
mallocs on small strings) and 64k bytes (to avoid overusing the
heap if *size was garbage). */
c->max = *size;
if (c->max < 64)
c->max = 64;
else if (c->max > 64 * 1024)
c->max = 64 * 1024;
*size = 0;
*buf = malloc (c->max);
if (!*buf)
{
fp->_flags = 0; /* release */
free (c);
return NULL;
}
**buf = '\0';
c->storage = c;
c->pbuf = buf;
c->psize = size;
c->eof = 0;
c->saved = '\0';
fp->_file = -1;
fp->_flags = __SWR;
fp->_cookie = c;
fp->_read = NULL;
fp->_write = memwrite;
fp->_seek = memseek;
fp->_close = memclose;
return fp;
}
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/stdio/open_memstream.c
|
C
|
asf20
| 6,619
|
#ifndef LEPTONICA__STDIO_H
#define LEPTONICA__STDIO_H
#ifndef BUILD_HOST
#include <stdio.h>
#include <stdint.h>
typedef struct cookie_io_functions_t {
ssize_t (*read)(void *cookie, char *buf, size_t n);
ssize_t (*write)(void *cookie, const char *buf, size_t n);
int (*seek)(void *cookie, off_t *pos, int whence);
int (*close)(void *cookie);
} cookie_io_functions_t;
FILE *fopencookie(void *cookie, const char *mode, cookie_io_functions_t functions);
FILE *fmemopen(void *buf, size_t size, const char *mode);
FILE *open_memstream(char **buf, size_t *size);
#endif
#endif /* LEPTONICA__STDIO_H */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/stdio/extrastdio.h
|
C
|
asf20
| 615
|
/* Copyright (C) 2007 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*
* Modifications for Android written Jul 2009 by Alan Viverette
*/
/*
FUNCTION
<<fopencookie>>---open a stream with custom callbacks
INDEX
fopencookie
ANSI_SYNOPSIS
#include <stdio.h>
typedef ssize_t (*cookie_read_function_t)(void *_cookie, char *_buf,
size_t _n);
typedef ssize_t (*cookie_write_function_t)(void *_cookie,
const char *_buf, size_t _n);
typedef int (*cookie_seek_function_t)(void *_cookie, off_t *_off,
int _whence);
typedef int (*cookie_close_function_t)(void *_cookie);
FILE *fopencookie(const void *<[cookie]>, const char *<[mode]>,
cookie_io_functions_t <[functions]>);
DESCRIPTION
<<fopencookie>> creates a <<FILE>> stream where I/O is performed using
custom callbacks. The callbacks are registered via the structure:
. typedef struct
. {
. cookie_read_function_t *read;
. cookie_write_function_t *write;
. cookie_seek_function_t *seek;
. cookie_close_function_t *close;
. } cookie_io_functions_t;
The stream is opened with <[mode]> treated as in <<fopen>>. The
callbacks <[functions.read]> and <[functions.write]> may only be NULL
when <[mode]> does not require them.
<[functions.read]> should return -1 on failure, or else the number of
bytes read (0 on EOF). It is similar to <<read>>, except that
<[cookie]> will be passed as the first argument.
<[functions.write]> should return -1 on failure, or else the number of
bytes written. It is similar to <<write>>, except that <[cookie]>
will be passed as the first argument.
<[functions.seek]> should return -1 on failure, and 0 on success, with
*<[_off]> set to the current file position. It is a cross between
<<lseek>> and <<fseek>>, with the <[_whence]> argument interpreted in
the same manner. A NULL <[functions.seek]> makes the stream behave
similarly to a pipe in relation to stdio functions that require
positioning.
<[functions.close]> should return -1 on failure, or 0 on success. It
is similar to <<close>>, except that <[cookie]> will be passed as the
first argument. A NULL <[functions.close]> merely flushes all data
then lets <<fclose>> succeed. A failed close will still invalidate
the stream.
Read and write I/O functions are allowed to change the underlying
buffer on fully buffered or line buffered streams by calling
<<setvbuf>>. They are also not required to completely fill or empty
the buffer. They are not, however, allowed to change streams from
unbuffered to buffered or to change the state of the line buffering
flag. They must also be prepared to have read or write calls occur on
buffers other than the one most recently specified.
RETURNS
The return value is an open FILE pointer on success. On error,
<<NULL>> is returned, and <<errno>> will be set to EINVAL if a
function pointer is missing or <[mode]> is invalid, ENOMEM if the
stream cannot be created, or EMFILE if too many streams are already
open.
PORTABILITY
This function is a newlib extension, copying the prototype from Linux.
It is not portable. See also the <<funopen>> interface from BSD.
Supporting OS subroutines required: <<sbrk>>.
*/
#include <stdio.h>
#include <errno.h>
#include <malloc.h>
#include "extrastdio.h"
typedef struct fccookie {
void *cookie;
FILE *fp;
ssize_t (*readfn)(void *, char *, size_t);
ssize_t (*writefn)(void *, const char *, size_t);
int (*seekfn)(void *, off_t *, int);
int (*closefn)(void *);
} fccookie;
static int
fcread(void *cookie, char *buf, int n)
{
int result;
fccookie *c = (fccookie *) cookie;
result = c->readfn (c->cookie, buf, n);
return result;
}
static int
fcwrite(void *cookie, const char *buf, int n)
{
int result;
fccookie *c = (fccookie *) cookie;
if (c->fp->_flags & __SAPP && c->fp->_seek)
{
c->fp->_seek (cookie, 0, SEEK_END);
}
result = c->writefn (c->cookie, buf, n);
return result;
}
static fpos_t
fcseek(void *cookie, fpos_t pos, int whence)
{
fccookie *c = (fccookie *) cookie;
off_t offset = (off_t) pos;
c->seekfn (c->cookie, &offset, whence);
return (fpos_t) offset;
}
static int
fcclose(void *cookie)
{
int result = 0;
fccookie *c = (fccookie *) cookie;
if (c->closefn)
{
result = c->closefn (c->cookie);
}
free (c);
return result;
}
FILE *
fopencookie(void *cookie, const char *mode, cookie_io_functions_t functions)
{
FILE *fp;
fccookie *c;
int flags;
int dummy;
if ((flags = __sflags (mode, &dummy)) == 0)
return NULL;
if (((flags & (__SRD | __SRW)) && !functions.read)
|| ((flags & (__SWR | __SRW)) && !functions.write))
{
return NULL;
}
if ((fp = (FILE *) __sfp ()) == NULL)
return NULL;
if ((c = (fccookie *) malloc (sizeof *c)) == NULL)
{
fp->_flags = 0;
return NULL;
}
fp->_file = -1;
fp->_flags = flags;
c->cookie = cookie;
c->fp = fp;
fp->_cookie = c;
c->readfn = functions.read;
fp->_read = fcread;
c->writefn = functions.write;
fp->_write = fcwrite;
c->seekfn = functions.seek;
fp->_seek = functions.seek ? fcseek : NULL;
c->closefn = functions.close;
fp->_close = fcclose;
return fp;
}
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/stdio/fopencookie.c
|
C
|
asf20
| 5,247
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include <string.h>
#include <android/bitmap.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*************
* WriteFile *
*************/
jint Java_com_googlecode_leptonica_android_WriteFile_nativeWriteBytes8(JNIEnv *env, jclass clazz,
jint nativePix,
jbyteArray data) {
l_int32 w, h, d;
PIX *pix = (PIX *) nativePix;
pixGetDimensions(pix, &w, &h, &d);
l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);
jbyte *data_buffer = env->GetByteArrayElements(data, NULL);
l_uint8 *byte_buffer = (l_uint8 *) data_buffer;
for (int i = 0; i < h; i++) {
memcpy((byte_buffer + (i * w)), lineptrs[i], w);
}
env->ReleaseByteArrayElements(data, data_buffer, 0);
pixCleanupByteProcessing(pix, lineptrs);
return (jint)(w * h);
}
jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteFiles(JNIEnv *env,
jclass clazz,
jint nativePixa,
jstring rootName,
jint format) {
PIXA *pixas = (PIXA *) nativePixa;
const char *c_rootName = env->GetStringUTFChars(rootName, NULL);
if (c_rootName == NULL) {
LOGE("could not extract rootName string!");
return JNI_FALSE;
}
jboolean result = JNI_TRUE;
if (pixaWriteFiles(c_rootName, pixas, (l_uint32) format)) {
LOGE("could not write pixa data to %s", c_rootName);
result = JNI_FALSE;
}
env->ReleaseStringUTFChars(rootName, c_rootName);
return result;
}
jbyteArray Java_com_googlecode_leptonica_android_WriteFile_nativeWriteMem(JNIEnv *env,
jclass clazz,
jint nativePix,
jint format) {
PIX *pixs = (PIX *) nativePix;
l_uint8 *data;
size_t size;
if (pixWriteMem(&data, &size, pixs, (l_uint32) format)) {
LOGE("Failed to write pix data");
return NULL;
}
// TODO Can we just use the byte array directly?
jbyteArray array = env->NewByteArray(size);
env->SetByteArrayRegion(array, 0, size, (jbyte *) data);
free(data);
return array;
}
jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteImpliedFormat(
JNIEnv *env,
jclass clazz,
jint nativePix,
jstring fileName,
jint quality,
jboolean progressive) {
PIX *pixs = (PIX *) nativePix;
const char *c_fileName = env->GetStringUTFChars(fileName, NULL);
if (c_fileName == NULL) {
LOGE("could not extract fileName string!");
return JNI_FALSE;
}
jboolean result = JNI_TRUE;
if (pixWriteImpliedFormat(c_fileName, pixs, (l_int32) quality, (progressive == JNI_TRUE))) {
LOGE("could not write pix data to %s", c_fileName);
result = JNI_FALSE;
}
env->ReleaseStringUTFChars(fileName, c_fileName);
return result;
}
jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteBitmap(JNIEnv *env,
jclass clazz,
jint nativePix,
jobject bitmap) {
PIX *pixs = (PIX *) nativePix;
l_int32 w, h, d;
AndroidBitmapInfo info;
void* pixels;
int ret;
if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
return JNI_FALSE;
}
if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
LOGE("Bitmap format is not RGBA_8888 !");
return JNI_FALSE;
}
pixGetDimensions(pixs, &w, &h, &d);
if (w != info.width || h != info.height) {
LOGE("Bitmap width and height do not match Pix dimensions!");
return JNI_FALSE;
}
if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
return JNI_FALSE;
}
pixEndianByteSwap(pixs);
l_uint8 *dst = (l_uint8 *) pixels;
l_uint8 *src = (l_uint8 *) pixGetData(pixs);
l_int32 dstBpl = info.stride;
l_int32 srcBpl = 4 * pixGetWpl(pixs);
LOGE("Writing 32bpp RGBA bitmap (w=%d, h=%d, stride=%d) from %dbpp Pix (wpl=%d)", info.width,
info.height, info.stride, d, pixGetWpl(pixs));
for (int dy = 0; dy < info.height; dy++) {
l_uint8 *dstx = dst;
l_uint8 *srcx = src;
if (d == 32) {
memcpy(dst, src, 4 * info.width);
} else if (d == 8) {
for (int dw = 0; dw < info.width; dw++) {
dstx[0] = dstx[1] = dstx[2] = srcx[0];
dstx[3] = 0xFF;
dstx += 4;
srcx += 1;
}
} else if (d == 1) {
for (int dw = 0; dw < info.width; dw++) {
dstx[0] = dstx[1] = dstx[2] = (srcx[0] & (dw % 8)) ? 0xFF : 0x00;
dstx[3] = 0xFF;
dstx += 4;
srcx += ((dw % 8) == 7) ? 1 : 0;
}
}
dst += dstBpl;
src += srcBpl;
}
AndroidBitmap_unlockPixels(env, bitmap);
return JNI_TRUE;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/writefile.cpp
|
C++
|
asf20
| 6,498
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include <string.h>
#include <android/bitmap.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/***************
* AdaptiveMap *
***************/
jint Java_com_googlecode_leptonica_android_AdaptiveMap_nativeBackgroundNormMorph(JNIEnv *env,
jclass clazz,
jint nativePix,
jint reduction,
jint size,
jint bgval) {
// Normalizes the background of each element in pixa.
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixBackgroundNormMorph(pixs, NULL, (l_int32) reduction, (l_int32) size,
(l_int32) bgval);
return (jint) pixd;
}
/************
* Binarize *
************/
jint Java_com_googlecode_leptonica_android_Binarize_nativeOtsuAdaptiveThreshold(JNIEnv *env,
jclass clazz,
jint nativePix,
jint sizeX,
jint sizeY,
jint smoothX,
jint smoothY,
jfloat scoreFract) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd;
if (pixOtsuAdaptiveThreshold(pixs, (l_int32) sizeX, (l_int32) sizeY, (l_int32) smoothX,
(l_int32) smoothY, (l_float32) scoreFract, NULL, &pixd)) {
return (jint) 0;
}
return (jint) pixd;
}
/***********
* Convert *
***********/
jint Java_com_googlecode_leptonica_android_Convert_nativeConvertTo8(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixConvertTo8(pixs, FALSE);
return (jint) pixd;
}
/***********
* Enhance *
***********/
jint Java_com_googlecode_leptonica_android_Enhance_nativeUnsharpMasking(JNIEnv *env, jclass clazz,
jint nativePix,
jint halfwidth,
jfloat fract) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixUnsharpMasking(pixs, (l_int32) halfwidth, (l_float32) fract);
return (jint) pixd;
}
/**********
* JpegIO *
**********/
jbyteArray Java_com_googlecode_leptonica_android_JpegIO_nativeCompressToJpeg(JNIEnv *env,
jclass clazz,
jint nativePix,
jint quality,
jboolean progressive) {
PIX *pix = (PIX *) nativePix;
l_uint8 *data;
size_t size;
if (pixWriteMemJpeg(&data, &size, pix, (l_int32) quality, progressive == JNI_TRUE ? 1 : 0)) {
LOGE("Failed to write JPEG data");
return NULL;
}
// TODO Can we just use the byte array directly?
jbyteArray array = env->NewByteArray(size);
env->SetByteArrayRegion(array, 0, size, (jbyte *) data);
free(data);
return array;
}
/*********
* Scale *
*********/
jint Java_com_googlecode_leptonica_android_Scale_nativeScale(JNIEnv *env, jclass clazz,
jint nativePix, jfloat scaleX,
jfloat scaleY) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixScale(pixs, (l_float32) scaleX, (l_float32) scaleY);
return (jint) pixd;
}
/********
* Skew *
********/
jfloat Java_com_googlecode_leptonica_android_Skew_nativeFindSkew(JNIEnv *env, jclass clazz,
jint nativePix, jfloat sweepRange,
jfloat sweepDelta,
jint sweepReduction,
jint searchReduction,
jfloat searchMinDelta) {
// Corrects the rotation of each element in pixa to 0 degrees.
PIX *pixs = (PIX *) nativePix;
l_float32 angle, conf;
if (!pixFindSkewSweepAndSearch(pixs, &angle, &conf, (l_int32) sweepReduction,
(l_int32) searchReduction, (l_float32) sweepRange,
(l_int32) sweepDelta, (l_float32) searchMinDelta)) {
if (conf <= 0) {
return (jfloat) 0;
}
return (jfloat) angle;
}
return (jfloat) 0;
}
/**********
* Rotate *
**********/
jint Java_com_googlecode_leptonica_android_Rotate_nativeRotate(JNIEnv *env, jclass clazz,
jint nativePix, jfloat degrees,
jboolean quality) {
PIX *pixd;
PIX *pixs = (PIX *) nativePix;
l_float32 deg2rad = 3.1415926535 / 180.0;
l_float32 radians = degrees * deg2rad;
l_int32 w, h, bpp, type;
pixGetDimensions(pixs, &w, &h, &bpp);
if (bpp == 1 && quality == JNI_TRUE) {
pixd = pixRotateBinaryNice(pixs, radians, L_BRING_IN_WHITE);
} else {
type = quality == JNI_TRUE ? L_ROTATE_AREA_MAP : L_ROTATE_SAMPLING;
pixd = pixRotate(pixs, radians, type, L_BRING_IN_WHITE, 0, 0);
}
return (jint) pixd;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/utilities.cpp
|
C++
|
asf20
| 6,787
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
jint Java_com_googlecode_leptonica_android_Pixa_nativeCreate(JNIEnv *env, jclass clazz, jint size) {
PIXA *pixa = pixaCreate((l_int32) size);
return (jint) pixa;
}
jint Java_com_googlecode_leptonica_android_Pixa_nativeCopy(JNIEnv *env, jclass clazz,
jint nativePixa) {
PIXA *pixas = (PIXA *) nativePixa;
PIXA *pixad = pixaCopy(pixas, L_CLONE);
return (jint) pixad;
}
jint Java_com_googlecode_leptonica_android_Pixa_nativeSort(JNIEnv *env, jclass clazz,
jint nativePixa, jint field, jint order) {
PIXA *pixas = (PIXA *) nativePixa;
PIXA *pixad = pixaSort(pixas, field, order, NULL, L_CLONE);
return (jint) pixad;
}
void Java_com_googlecode_leptonica_android_Pixa_nativeDestroy(JNIEnv *env, jclass clazz,
jint nativePixa) {
PIXA *pixa = (PIXA *) nativePixa;
pixaDestroy(&pixa);
}
jboolean Java_com_googlecode_leptonica_android_Pixa_nativeJoin(JNIEnv *env, jclass clazz,
jint nativePixa, jint otherPixa) {
PIXA *pixa = (PIXA *) nativePixa;
PIXA *pixas = (PIXA *) otherPixa;
if (pixaJoin(pixa, pixas, 0, 0)) {
return JNI_FALSE;
}
return JNI_TRUE;
}
jint Java_com_googlecode_leptonica_android_Pixa_nativeGetCount(JNIEnv *env, jclass clazz,
jint nativePixa) {
PIXA *pixa = (PIXA *) nativePixa;
return (jint) pixaGetCount(pixa);
}
void Java_com_googlecode_leptonica_android_Pixa_nativeAddPix(JNIEnv *env, jclass clazz,
jint nativePixa, jint nativePix,
jint mode) {
PIXA *pixa = (PIXA *) nativePixa;
PIX *pix = (PIX *) nativePix;
pixaAddPix(pixa, pix, mode);
}
void Java_com_googlecode_leptonica_android_Pixa_nativeAddBox(JNIEnv *env, jclass clazz,
jint nativePixa, jint nativeBox,
jint mode) {
PIXA *pixa = (PIXA *) nativePixa;
BOX *box = (BOX *) nativeBox;
pixaAddBox(pixa, box, mode);
}
void Java_com_googlecode_leptonica_android_Pixa_nativeAdd(JNIEnv *env, jclass clazz,
jint nativePixa, jint nativePix,
jint nativeBox, jint mode) {
PIXA *pixa = (PIXA *) nativePixa;
PIX *pix = (PIX *) nativePix;
BOX *box = (BOX *) nativeBox;
pixaAddPix(pixa, pix, mode);
pixaAddBox(pixa, box, mode);
}
void Java_com_googlecode_leptonica_android_Pixa_nativeReplacePix(JNIEnv *env, jclass clazz,
jint nativePixa, jint index,
jint nativePix, jint nativeBox) {
PIXA *pixa = (PIXA *) nativePixa;
PIX *pix = (PIX *) nativePix;
BOX *box = (BOX *) nativeBox;
pixaReplacePix(pixa, index, pix, box);
}
void Java_com_googlecode_leptonica_android_Pixa_nativeMergeAndReplacePix(JNIEnv *env, jclass clazz,
jint nativePixa,
jint indexA, jint indexB) {
PIXA *pixa = (PIXA *) nativePixa;
l_int32 op;
l_int32 x, y, w, h;
l_int32 dx, dy, dw, dh;
PIX *pixs, *pixd;
BOX *boxA, *boxB, *boxd;
boxA = pixaGetBox(pixa, indexA, L_CLONE);
boxB = pixaGetBox(pixa, indexB, L_CLONE);
boxd = boxBoundingRegion(boxA, boxB);
boxGetGeometry(boxd, &x, &y, &w, &h);
pixd = pixCreate(w, h, 1);
op = PIX_SRC | PIX_DST;
pixs = pixaGetPix(pixa, indexA, L_CLONE);
boxGetGeometry(boxA, &dx, &dy, &dw, &dh);
pixRasterop(pixd, dx - x, dy - y, dw, dh, op, pixs, 0, 0);
pixDestroy(&pixs);
boxDestroy(&boxA);
pixs = pixaGetPix(pixa, indexB, L_CLONE);
boxGetGeometry(boxB, &dx, &dy, &dw, &dh);
pixRasterop(pixd, dx - x, dy - y, dw, dh, op, pixs, 0, 0);
pixDestroy(&pixs);
boxDestroy(&boxB);
pixaReplacePix(pixa, indexA, pixd, boxd);
}
jboolean Java_com_googlecode_leptonica_android_Pixa_nativeWriteToFileRandomCmap(JNIEnv *env,
jclass clazz,
jint nativePixa,
jstring fileName,
jint width,
jint height) {
PIX *pixtemp;
PIXA *pixa = (PIXA *) nativePixa;
const char *c_fileName = env->GetStringUTFChars(fileName, NULL);
if (c_fileName == NULL) {
LOGE("could not extract fileName string!");
return JNI_FALSE;
}
if (pixaGetCount(pixa) > 0) {
pixtemp = pixaDisplayRandomCmap(pixa, (l_int32) width, (l_int32) height);
} else {
pixtemp = pixCreate((l_int32) width, (l_int32) height, 1);
}
pixWrite(c_fileName, pixtemp, IFF_BMP);
pixDestroy(&pixtemp);
env->ReleaseStringUTFChars(fileName, c_fileName);
return JNI_TRUE;
}
jint Java_com_googlecode_leptonica_android_Pixa_nativeGetPix(JNIEnv *env, jclass clazz,
jint nativePixa, jint index) {
PIXA *pixa = (PIXA *) nativePixa;
PIX *pix = pixaGetPix(pixa, (l_int32) index, L_CLONE);
return (jint) pix;
}
jint Java_com_googlecode_leptonica_android_Pixa_nativeGetBox(JNIEnv *env, jclass clazz,
jint nativePixa, jint index) {
PIXA *pixa = (PIXA *) nativePixa;
BOX *box = pixaGetBox(pixa, (l_int32) index, L_CLONE);
return (jint) box;
}
jboolean Java_com_googlecode_leptonica_android_Pixa_nativeGetBoxGeometry(JNIEnv *env, jclass clazz,
jint nativePixa,
jint index,
jintArray dimensions) {
PIXA *pixa = (PIXA *) nativePixa;
jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL);
l_int32 x, y, w, h;
if (pixaGetBoxGeometry(pixa, (l_int32) index, &x, &y, &w, &h)) {
return JNI_FALSE;
}
dimensionArray[0] = x;
dimensionArray[1] = y;
dimensionArray[2] = w;
dimensionArray[3] = h;
env->ReleaseIntArrayElements(dimensions, dimensionArray, 0);
return JNI_TRUE;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/pixa.cpp
|
C++
|
asf20
| 7,478
|
/*
* Copyright 2010, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LEPTONICA_JNI_CONFIG_AUTO_H
#define LEPTONICA_JNI_CONFIG_AUTO_H
#define HAVE_LIBJPEG 0
#define HAVE_LIBTIFF 0
#define HAVE_LIBPNG 0
#define HAVE_LIBZ 1
#define HAVE_LIBGIF 0
#define HAVE_LIBUNGIF 0
#define HAVE_FMEMOPEN 1
#endif
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/config_auto.h
|
C
|
asf20
| 836
|
/*
* Copyright 2010, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LEPTONICA_JNI_COMMON_H
#define LEPTONICA_JNI_COMMON_H
#include <jni.h>
#include <assert.h>
#include <allheaders.h>
#include <android/log.h>
#include <asm/byteorder.h>
#ifdef __BIG_ENDIAN
#define SK_A32_SHIFT 0
#define SK_R32_SHIFT 8
#define SK_G32_SHIFT 16
#define SK_B32_SHIFT 24
#else
#define SK_A32_SHIFT 24
#define SK_R32_SHIFT 16
#define SK_G32_SHIFT 8
#define SK_B32_SHIFT 0
#endif /* __BIG_ENDIAN */
#define LOG_TAG "Leptonica(native)"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__)
#endif
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/common.h
|
C
|
asf20
| 1,571
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include <string.h>
#include <android/bitmap.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/************
* ReadFile *
************/
jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz,
jbyteArray image, jint length) {
jbyte *image_buffer = env->GetByteArrayElements(image, NULL);
int buffer_length = env->GetArrayLength(image);
PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length);
env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT);
return (jint) pix;
}
jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz,
jbyteArray data, jint w,
jint h) {
PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8);
l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);
jbyte *data_buffer = env->GetByteArrayElements(data, NULL);
l_uint8 *byte_buffer = (l_uint8 *) data_buffer;
for (int i = 0; i < h; i++) {
memcpy(lineptrs[i], (byte_buffer + (i * w)), w);
}
env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);
pixCleanupByteProcessing(pix, lineptrs);
l_int32 d;
pixGetDimensions(pix, &w, &h, &d);
LOGE("Created image width w=%d, h=%d, d=%d", w, h, d);
return (jint) pix;
}
jboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env,
jclass clazz,
jint nativePix,
jbyteArray data,
jint srcw, jint srch) {
PIX *pix = (PIX *) nativePix;
l_int32 w, h, d;
pixGetDimensions(pix, &w, &h, &d);
if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) {
LOGE("Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d", w, h, d, srcw, srch);
return JNI_FALSE;
}
l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);
jbyte *data_buffer = env->GetByteArrayElements(data, NULL);
l_uint8 *byte_buffer = (l_uint8 *) data_buffer;
for (int i = 0; i < h; i++) {
memcpy(lineptrs[i], (byte_buffer + (i * w)), w);
}
env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);
pixCleanupByteProcessing(pix, lineptrs);
return JNI_TRUE;
}
jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz,
jstring dirName, jstring prefix) {
PIXA *pixad = NULL;
const char *c_dirName = env->GetStringUTFChars(dirName, NULL);
if (c_dirName == NULL) {
LOGE("could not extract dirName string!");
return NULL;
}
const char *c_prefix = env->GetStringUTFChars(prefix, NULL);
if (c_prefix == NULL) {
LOGE("could not extract prefix string!");
return NULL;
}
pixad = pixaReadFiles(c_dirName, c_prefix);
env->ReleaseStringUTFChars(dirName, c_dirName);
env->ReleaseStringUTFChars(prefix, c_prefix);
return (jint) pixad;
}
jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz,
jstring fileName) {
PIX *pixd = NULL;
const char *c_fileName = env->GetStringUTFChars(fileName, NULL);
if (c_fileName == NULL) {
LOGE("could not extract fileName string!");
return NULL;
}
pixd = pixRead(c_fileName);
env->ReleaseStringUTFChars(fileName, c_fileName);
return (jint) pixd;
}
jint Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz,
jobject bitmap) {
l_int32 w, h, d;
AndroidBitmapInfo info;
void* pixels;
int ret;
if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
return JNI_FALSE;
}
if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
LOGE("Bitmap format is not RGBA_8888 !");
return JNI_FALSE;
}
if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
return JNI_FALSE;
}
PIX *pixd = pixCreate(info.width, info.height, 8);
l_uint32 *src = (l_uint32 *) pixels;
l_int32 srcWpl = (info.stride / 4);
l_uint32 *dst = pixGetData(pixd);
l_int32 dstWpl = pixGetWpl(pixd);
l_uint8 a, r, g, b, pixel8;
for (int y = 0; y < info.height; y++) {
l_uint32 *dst_line = dst + (y * dstWpl);
l_uint32 *src_line = src + (y * srcWpl);
for (int x = 0; x < info.width; x++) {
// Get pixel from RGBA_8888
r = *src_line >> SK_R32_SHIFT;
g = *src_line >> SK_G32_SHIFT;
b = *src_line >> SK_B32_SHIFT;
a = *src_line >> SK_A32_SHIFT;
pixel8 = (l_uint8)((r + g + b) / 3);
// Set pixel to LUMA_8
SET_DATA_BYTE(dst_line, x, pixel8);
// Move to the next pixel
src_line++;
}
}
AndroidBitmap_unlockPixels(env, bitmap);
return (jint) pixd;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/readfile.cpp
|
C++
|
asf20
| 5,975
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
jint Java_com_googlecode_leptonica_android_Box_nativeCreate(JNIEnv *env, jclass clazz, jint x,
jint y, jint w, jint h) {
BOX *box = boxCreate((l_int32) x, (l_int32) y, (l_int32) w, (l_int32) h);
return (jint) box;
}
void Java_com_googlecode_leptonica_android_Box_nativeDestroy(JNIEnv *env, jclass clazz,
jint nativeBox) {
BOX *box = (BOX *) nativeBox;
boxDestroy(&box);
}
jint Java_com_googlecode_leptonica_android_Box_nativeGetX(JNIEnv *env, jclass clazz, jint nativeBox) {
BOX *box = (BOX *) nativeBox;
return (jint) box->x;
}
jint Java_com_googlecode_leptonica_android_Box_nativeGetY(JNIEnv *env, jclass clazz, jint nativeBox) {
BOX *box = (BOX *) nativeBox;
return (jint) box->y;
}
jint Java_com_googlecode_leptonica_android_Box_nativeGetWidth(JNIEnv *env, jclass clazz,
jint nativeBox) {
BOX *box = (BOX *) nativeBox;
return (jint) box->w;
}
jint Java_com_googlecode_leptonica_android_Box_nativeGetHeight(JNIEnv *env, jclass clazz,
jint nativeBox) {
BOX *box = (BOX *) nativeBox;
return (jint) box->h;
}
jboolean Java_com_googlecode_leptonica_android_Box_nativeGetGeometry(JNIEnv *env, jclass clazz,
jint nativeBox,
jintArray dimensions) {
BOX *box = (BOX *) nativeBox;
jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL);
l_int32 x, y, w, h;
if (boxGetGeometry(box, &x, &y, &w, &h)) {
return JNI_FALSE;
}
dimensionArray[0] = x;
dimensionArray[1] = y;
dimensionArray[2] = w;
dimensionArray[3] = h;
env->ReleaseIntArrayElements(dimensions, dimensionArray, 0);
return JNI_TRUE;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/box.cpp
|
C++
|
asf20
| 2,672
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
jint Java_com_googlecode_leptonica_android_Pix_nativeCreatePix(JNIEnv *env, jclass clazz, jint w,
jint h, jint d) {
PIX *pix = pixCreate((l_int32) w, (l_int32) h, (l_int32) d);
return (jint) pix;
}
jint Java_com_googlecode_leptonica_android_Pix_nativeCreateFromData(JNIEnv *env, jclass clazz,
jbyteArray data, jint w,
jint h, jint d) {
PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, (l_int32) d);
jbyte *data_buffer = env->GetByteArrayElements(data, NULL);
l_uint8 *byte_buffer = (l_uint8 *) data_buffer;
size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix);
memcpy(pixGetData(pix), byte_buffer, size);
env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);
return (jint) pix;
}
jboolean Java_com_googlecode_leptonica_android_Pix_nativeGetData(JNIEnv *env, jclass clazz,
jint nativePix, jbyteArray data) {
PIX *pix = (PIX *) nativePix;
jbyte *data_buffer = env->GetByteArrayElements(data, NULL);
l_uint8 *byte_buffer = (l_uint8 *) data_buffer;
size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix);
memcpy(byte_buffer, pixGetData(pix), size);
env->ReleaseByteArrayElements(data, data_buffer, 0);
return JNI_TRUE;
}
jint Java_com_googlecode_leptonica_android_Pix_nativeGetDataSize(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pix = (PIX *) nativePix;
size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix);
return (jint) size;
}
jint Java_com_googlecode_leptonica_android_Pix_nativeClone(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixClone(pixs);
return (jint) pixd;
}
jint Java_com_googlecode_leptonica_android_Pix_nativeCopy(JNIEnv *env, jclass clazz, jint nativePix) {
PIX *pixs = (PIX *) nativePix;
PIX *pixd = pixCopy(NULL, pixs);
return (jint) pixd;
}
jboolean Java_com_googlecode_leptonica_android_Pix_nativeInvert(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pixs = (PIX *) nativePix;
if (pixInvert(pixs, pixs)) {
return JNI_FALSE;
}
return JNI_TRUE;
}
void Java_com_googlecode_leptonica_android_Pix_nativeDestroy(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pix = (PIX *) nativePix;
pixDestroy(&pix);
}
jboolean Java_com_googlecode_leptonica_android_Pix_nativeGetDimensions(JNIEnv *env, jclass clazz,
jint nativePix,
jintArray dimensions) {
PIX *pix = (PIX *) nativePix;
jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL);
l_int32 w, h, d;
if (pixGetDimensions(pix, &w, &h, &d)) {
return JNI_FALSE;
}
dimensionArray[0] = w;
dimensionArray[1] = h;
dimensionArray[2] = d;
env->ReleaseIntArrayElements(dimensions, dimensionArray, 0);
return JNI_TRUE;
}
jint Java_com_googlecode_leptonica_android_Pix_nativeGetWidth(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pix = (PIX *) nativePix;
return (jint) pixGetWidth(pix);
}
jint Java_com_googlecode_leptonica_android_Pix_nativeGetHeight(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pix = (PIX *) nativePix;
return (jint) pixGetHeight(pix);
}
jint Java_com_googlecode_leptonica_android_Pix_nativeGetDepth(JNIEnv *env, jclass clazz,
jint nativePix) {
PIX *pix = (PIX *) nativePix;
return (jint) pixGetDepth(pix);
}
void Java_com_googlecode_leptonica_android_Pix_nativeSetPixel(JNIEnv *env, jclass clazz,
jint nativePix, jint xCoord,
jint yCoord, jint argbColor) {
PIX *pix = (PIX *) nativePix;
l_int32 d = pixGetDepth(pix);
l_int32 x = (l_int32) xCoord;
l_int32 y = (l_int32) yCoord;
// These shift values are based on RGBA_8888
l_uint8 r = (argbColor >> SK_R32_SHIFT) & 0xFF;
l_uint8 g = (argbColor >> SK_G32_SHIFT) & 0xFF;
l_uint8 b = (argbColor >> SK_B32_SHIFT) & 0xFF;
l_uint8 a = (argbColor >> SK_A32_SHIFT) & 0xFF;
l_uint8 gray = ((r + g + b) / 3) & 0xFF;
l_uint32 color;
switch (d) {
case 1: // 1-bit binary
color = gray > 128 ? 1 : 0;
break;
case 2: // 2-bit grayscale
color = gray >> 6;
break;
case 4: // 4-bit grayscale
color = gray >> 4;
break;
case 8: // 8-bit grayscale
color = gray;
break;
case 24: // 24-bit RGB
SET_DATA_BYTE(&color, COLOR_RED, r);
SET_DATA_BYTE(&color, COLOR_GREEN, g);
SET_DATA_BYTE(&color, COLOR_BLUE, b);
break;
case 32: // 32-bit ARGB
SET_DATA_BYTE(&color, COLOR_RED, r);
SET_DATA_BYTE(&color, COLOR_GREEN, g);
SET_DATA_BYTE(&color, COLOR_BLUE, b);
SET_DATA_BYTE(&color, L_ALPHA_CHANNEL, a);
break;
default: // unsupported
LOGE("Not a supported color depth: %d", d);
color = 0;
break;
}
pixSetPixel(pix, x, y, color);
}
jint Java_com_googlecode_leptonica_android_Pix_nativeGetPixel(JNIEnv *env, jclass clazz,
jint nativePix, jint xCoord,
jint yCoord) {
PIX *pix = (PIX *) nativePix;
l_int32 d = pixGetDepth(pix);
l_int32 x = (l_int32) xCoord;
l_int32 y = (l_int32) yCoord;
l_uint32 pixel;
l_uint32 color;
l_uint8 a, r, g, b;
pixGetPixel(pix, x, y, &pixel);
switch (d) {
case 1: // 1-bit binary
a = 0xFF;
r = g = b = (pixel == 0 ? 0x00 : 0xFF);
break;
case 2: // 2-bit grayscale
a = 0xFF;
r = g = b = (pixel << 6 | pixel << 4 | pixel);
break;
case 4: // 4-bit grayscale
a = 0xFF;
r = g = b = (pixel << 4 | pixel);
break;
case 8: // 8-bit grayscale
a = 0xFF;
r = g = b = pixel;
break;
case 24: // 24-bit RGB
a = 0xFF;
r = (pixel >> L_RED_SHIFT) & 0xFF;
g = (pixel >> L_GREEN_SHIFT) & 0xFF;
b = (pixel >> L_BLUE_SHIFT) & 0xFF;
break;
case 32: // 32-bit RGBA
r = (pixel >> L_RED_SHIFT) & 0xFF;
g = (pixel >> L_GREEN_SHIFT) & 0xFF;
b = (pixel >> L_BLUE_SHIFT) & 0xFF;
a = (pixel >> L_ALPHA_SHIFT) & 0xFF;
break;
default: // Not supported
LOGE("Not a supported color depth: %d", d);
a = r = g = b = 0x00;
break;
}
color = a << SK_A32_SHIFT;
color |= r << SK_R32_SHIFT;
color |= g << SK_G32_SHIFT;
color |= b << SK_B32_SHIFT;
return (jint) color;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/pix.cpp
|
C++
|
asf20
| 7,886
|
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := liblept
# leptonica (minus freetype)
BLACKLIST_SRC_FILES := \
%endiantest.c \
%freetype.c \
%xtractprotos.c
LEPTONICA_SRC_FILES := \
$(subst $(LOCAL_PATH)/,,$(wildcard $(LEPTONICA_PATH)/src/*.c))
LOCAL_SRC_FILES := \
$(filter-out $(BLACKLIST_SRC_FILES),$(LEPTONICA_SRC_FILES))
LOCAL_CFLAGS := \
-DHAVE_CONFIG_H
LOCAL_LDLIBS := \
-lz
# missing stdio functions
ifneq ($(TARGET_SIMULATOR),true)
LOCAL_SRC_FILES += \
stdio/open_memstream.c \
stdio/fopencookie.c \
stdio/fmemopen.c
LOCAL_C_INCLUDES += \
stdio
endif
# jni
LOCAL_SRC_FILES += \
box.cpp \
pix.cpp \
pixa.cpp \
utilities.cpp \
readfile.cpp \
writefile.cpp \
jni.cpp
LOCAL_C_INCLUDES += \
$(LOCAL_PATH) \
$(LEPTONICA_PATH)/src
LOCAL_LDLIBS += \
-ljnigraphics \
-llog
# common
LOCAL_PRELINK_MODULE:= false
include $(BUILD_SHARED_LIBRARY)
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/Android.mk
|
Makefile
|
asf20
| 924
|
/*
* Copyright 2011, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv *env;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) {
LOGE("ERROR: GetEnv failed\n");
return -1;
}
assert(env != NULL);
return JNI_VERSION_1_6;
}
|
1006373c-hello
|
tesseract-android-tools/jni/com_googlecode_leptonica_android/jni.cpp
|
C++
|
asf20
| 853
|
APP_STL := gnustl_static
APP_ABI := armeabi armeabi-v7a x86 # mips has problems with gnustl_static
APP_OPTIM := release
APP_PLATFORM := android-8
APP_CPPFLAGS += -fexceptions -frtti
|
1006373c-hello
|
tesseract-android-tools/jni/Application.mk
|
Makefile
|
asf20
| 182
|
LOCAL_PATH := $(call my-dir)
TESSERACT_PATH := $(LOCAL_PATH)/com_googlecode_tesseract_android/src
LEPTONICA_PATH := $(LOCAL_PATH)/com_googlecode_leptonica_android/src
# Just build the Android.mk files in the subdirs
include $(call all-subdir-makefiles)
|
1006373c-hello
|
tesseract-android-tools/jni/Android.mk
|
Makefile
|
asf20
| 254
|
// Copyright (c) 2013 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.dongxiguo.protobuf;
import com.dongxiguo.utils.HaxelibRun;
import sys.io.File;
import sys.FileSystem;
class Run
{
static function main()
{
var args = Sys.args();
var returnValue = HaxelibRun.run(args);
if (returnValue == null)
{
switch (args[0])
{
case "protoc":
var libPath = Sys.getCwd();
var cwd = args.pop();
Sys.setCwd(cwd);
var pluginScriptFileName = cwd + (Sys.systemName() == "Windows" ? "protoc-gen-as3.tmp.bat" : "protoc-gen-as3.tmp.sh");
File.saveContent(pluginScriptFileName, Sys.systemName() == "Windows" ? '@"$libPath\\protoc-gen-as3.bat"' : '#!/bin/sh
"$libPath/protoc-gen-as3"');
if (Sys.systemName() == "Windows")
{
Sys.command("cacls", [pluginScriptFileName, "/E", "/G", "Everyone:R"]);
}
else
{
Sys.command("chmod", ["+x", pluginScriptFileName]);
}
args[0] = '--plugin=protoc-gen-as3=$pluginScriptFileName';
var returnValue = Sys.command("protoc", args);
FileSystem.deleteFile(pluginScriptFileName);
Sys.exit(returnValue);
default:
Sys.print('Usage: haxelib run ${HaxelibRun.libraryName()} protoc [ args ... ]
${HaxelibRun.usage()}');
Sys.exit(-1);
}
}
else
{
Sys.exit(returnValue);
}
}
}
// vim: sts=2 sw=2 et
|
118194141-test
|
hx/com/dongxiguo/protobuf/Run.hx
|
Haxe
|
bsd
| 1,655
|
// vim: fileencoding=utf-8 tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protocGenAs3;
import static google.protobuf.compiler.Plugin.*;
import static com.google.protobuf.DescriptorProtos.*;
import com.google.protobuf.*;
import java.io.*;
import java.util.*;
import java.math.*;
public final class Main {
private static final String[] ACTIONSCRIPT_KEYWORDS = {
"as", "break", "case", "catch", "class", "const", "continue", "default",
"delete", "do", "else", "extends", "false", "finally", "for",
"function", "if", "implements", "import", "in", "instanceof",
"interface", "internal", "is", "native", "new", "null", "package",
"private", "protected", "public", "return", "super", "switch", "this",
"throw", "to", "true", "try", "typeof", "use", "var", "void", "while",
"with"
};
private static final class Scope<Proto> {
// 如果 proto instanceOf Scope ,则这个 Scope 是对另一 Scope 的引用
public final String fullName;
public final Scope<?> parent;
public final Proto proto;
public final boolean export;
public final HashMap<String, Scope<?>> children =
new HashMap<String, Scope<?>>();
private Scope<?> find(String[] pathElements, int i) {
Scope<?> result = this;
for (; i < pathElements.length; i++) {
String name = pathElements[i];
if (result.children.containsKey(name)) {
result = result.children.get(name);
} else {
return null;
}
}
while (result.proto instanceof Scope) {
result = (Scope<?>)result.proto;
}
return result;
}
public boolean isRoot() {
return parent == null;
}
private Scope<?> getRoot() {
Scope<?> scope = this;
while (!scope.isRoot()) {
scope = scope.parent;
}
return scope;
}
public Scope<?> find(String path) {
String[] pathElements = path.split("\\.");
if (pathElements[0].equals("")) {
return getRoot().find(pathElements, 1);
} else {
for (Scope<?> scope = this; scope != null; scope = scope.parent) {
Scope<?> result = scope.find(pathElements, 0);
if (result != null) {
return result;
}
}
return null;
}
}
private Scope<?> findOrCreate(String[] pathElements, int i) {
Scope<?> scope = this;
for (; i < pathElements.length; i++) {
String name = pathElements[i];
if (scope.children.containsKey(name)) {
scope = scope.children.get(name);
} else {
Scope<Object> child =
new Scope<Object>(scope, null, false, name);
scope.children.put(name, child);
scope = child;
}
}
return scope;
}
public Scope<?> findOrCreate(String path) {
String[] pathElements = path.split("\\.");
if (pathElements[0].equals("")) {
return getRoot().findOrCreate(pathElements, 1);
} else {
return findOrCreate(pathElements, 0);
}
}
private Scope(Scope<?> parent, Proto proto, boolean export,
String name) {
this.parent = parent;
this.proto = proto;
this.export = export;
if (isRoot() || parent.isRoot()) {
fullName = name;
} else {
fullName = parent.fullName + '.' + name;
}
}
public <ChildProto> Scope<ChildProto> addChild(
String name, ChildProto proto, boolean export) {
assert(name != null);
assert(!name.equals(""));
Scope<ChildProto> child =
new Scope<ChildProto>(this, proto, export, name);
if(children.containsKey(child)) {
throw new IllegalArgumentException();
}
children.put(name, child);
return child;
}
public static Scope<Object> newRoot() {
return new Scope<Object>(null, null, false, "");
}
}
private static void addServiceToScope(Scope<?> scope,
ServiceDescriptorProto sdp, boolean export) {
scope.addChild(sdp.getName(), sdp, export);
}
private static void addExtensionToScope(Scope<?> scope,
FieldDescriptorProto efdp, boolean export) {
scope.addChild(efdp.getName().toUpperCase(), efdp, export);
}
private static void addEnumToScope(Scope<?> scope, EnumDescriptorProto edp,
boolean export) {
assert(edp.hasName());
Scope<EnumDescriptorProto> enumScope =
scope.addChild(edp.getName(), edp, export);
for (EnumValueDescriptorProto evdp : edp.getValueList()) {
Scope<EnumValueDescriptorProto> enumValueScope =
enumScope.addChild(evdp.getName(), evdp, false);
scope.addChild(evdp.getName(), enumValueScope, false);
}
}
private static void addMessageToScope(Scope<?> scope, DescriptorProto dp,
boolean export) {
Scope<DescriptorProto> messageScope =
scope.addChild(dp.getName(), dp, export);
for (EnumDescriptorProto edp : dp.getEnumTypeList()) {
addEnumToScope(messageScope, edp, export);
}
for (DescriptorProto nested: dp.getNestedTypeList()) {
addMessageToScope(messageScope, nested, export);
}
}
private static Scope<Object> buildScopeTree(CodeGeneratorRequest request) {
Scope<Object> root = Scope.newRoot();
List<String> filesToGenerate = request.getFileToGenerateList();
for (FileDescriptorProto fdp : request.getProtoFileList()) {
Scope<?> packageScope = fdp.hasPackage() ?
root.findOrCreate(fdp.getPackage()) : root;
boolean export = filesToGenerate.contains(fdp.getName());
for (ServiceDescriptorProto sdp : fdp.getServiceList()) {
addServiceToScope(packageScope, sdp, export);
}
for (FieldDescriptorProto efdp : fdp.getExtensionList()) {
addExtensionToScope(packageScope, efdp, export);
}
for (EnumDescriptorProto edp : fdp.getEnumTypeList()) {
addEnumToScope(packageScope, edp, export);
}
for (DescriptorProto dp : fdp.getMessageTypeList()) {
addMessageToScope(packageScope, dp, export);
}
}
return root;
}
private static String getImportType(Scope<?> scope,
FieldDescriptorProto fdp) {
switch (fdp.getType()) {
case TYPE_ENUM:
case TYPE_MESSAGE:
Scope<?> typeScope = scope.find(fdp.getTypeName());
if (typeScope == null) {
throw new IllegalArgumentException(
fdp.getTypeName() + " not found.");
}
return typeScope.fullName;
case TYPE_BYTES:
return "flash.utils.ByteArray";
default:
return null;
}
}
private static boolean isValueType(FieldDescriptorProto.Type type) {
switch (type) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_INT32:
case TYPE_FIXED32:
case TYPE_BOOL:
case TYPE_UINT32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_ENUM:
return true;
default:
return false;
}
}
static final int VARINT = 0;
static final int FIXED_64_BIT = 1;
static final int LENGTH_DELIMITED = 2;
static final int FIXED_32_BIT = 5;
private static int getWireType(
FieldDescriptorProto.Type type) {
switch (type) {
case TYPE_DOUBLE:
case TYPE_FIXED64:
case TYPE_SFIXED64:
return FIXED_64_BIT;
case TYPE_FLOAT:
case TYPE_FIXED32:
case TYPE_SFIXED32:
return FIXED_32_BIT;
case TYPE_INT32:
case TYPE_SINT32:
case TYPE_UINT32:
case TYPE_BOOL:
case TYPE_INT64:
case TYPE_UINT64:
case TYPE_SINT64:
case TYPE_ENUM:
return VARINT;
case TYPE_STRING:
case TYPE_MESSAGE:
case TYPE_BYTES:
return LENGTH_DELIMITED;
default:
throw new IllegalArgumentException();
}
}
private static String getActionScript3WireType(
FieldDescriptorProto.Type type) {
switch (type) {
case TYPE_DOUBLE:
case TYPE_FIXED64:
case TYPE_SFIXED64:
return "FIXED_64_BIT";
case TYPE_FLOAT:
case TYPE_FIXED32:
case TYPE_SFIXED32:
return "FIXED_32_BIT";
case TYPE_INT32:
case TYPE_SINT32:
case TYPE_UINT32:
case TYPE_BOOL:
case TYPE_INT64:
case TYPE_UINT64:
case TYPE_SINT64:
case TYPE_ENUM:
return "VARINT";
case TYPE_STRING:
case TYPE_MESSAGE:
case TYPE_BYTES:
return "LENGTH_DELIMITED";
default:
throw new IllegalArgumentException();
}
}
private static String getActionScript3LogicType(Scope<?> scope,
FieldDescriptorProto fdp) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_ENUM) {
Scope<?> typeScope = scope.find(fdp.getTypeName());
if (typeScope == null) {
throw new IllegalArgumentException(
fdp.getTypeName() + " not found.");
}
if (typeScope == scope) {
// workaround for mxmlc's bug.
return typeScope.fullName.substring(
typeScope.fullName.lastIndexOf('.') + 1);
}
return typeScope.fullName;
} else {
return getActionScript3Type(scope, fdp);
}
}
private static String getActionScript3Type(Scope<?> scope,
FieldDescriptorProto fdp) {
switch (fdp.getType()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
return "Number";
case TYPE_INT32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_ENUM:
return "int";
case TYPE_UINT32:
case TYPE_FIXED32:
return "uint";
case TYPE_BOOL:
return "Boolean";
case TYPE_INT64:
case TYPE_SFIXED64:
case TYPE_SINT64:
return "Int64";
case TYPE_UINT64:
case TYPE_FIXED64:
return "UInt64";
case TYPE_STRING:
return "String";
case TYPE_MESSAGE:
Scope<?> typeScope = scope.find(fdp.getTypeName());
if (typeScope == null) {
throw new IllegalArgumentException(
fdp.getTypeName() + " not found.");
}
if (typeScope == scope) {
// workaround for mxmlc's bug.
return typeScope.fullName.substring(
typeScope.fullName.lastIndexOf('.') + 1);
}
return typeScope.fullName;
case TYPE_BYTES:
return "flash.utils.ByteArray";
default:
throw new IllegalArgumentException();
}
}
private static void appendQuotedString(StringBuilder sb, String value) {
sb.append('\"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '\"':
case '\\':
sb.append('\\');
sb.append(c);
break;
default:
if (c >= 128 || Character.isISOControl(c)) {
sb.append("\\u");
sb.append(String.format("%04X", new Integer(c)));
} else {
sb.append(c);
}
}
}
sb.append('\"');
}
private static void appendDefaultValue(StringBuilder sb, Scope<?> scope,
FieldDescriptorProto fdp) {
String value = fdp.getDefaultValue();
switch (fdp.getType()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
if (value.equals("nan")) {
sb.append("NaN");
} else if (value.equals("inf")) {
sb.append("Infinity");
} else if (value.equals("-inf")) {
sb.append("-Infinity");
} else {
sb.append(value);
}
break;
case TYPE_UINT64:
case TYPE_FIXED64:
{
long v = new BigInteger(value).longValue();
sb.append("new UInt64(");
sb.append(Long.toString(v & 0xFFFFFFFFL));
sb.append(", ");
sb.append(Long.toString((v >>> 32) & 0xFFFFFFFFL));
sb.append(")");
}
break;
case TYPE_INT64:
case TYPE_SFIXED64:
case TYPE_SINT64:
{
long v = Long.parseLong(value);
sb.append("new Int64(");
sb.append(Long.toString(v & 0xFFFFFFFFL));
sb.append(", ");
sb.append(Integer.toString((int)v >>> 32));
sb.append(")");
}
break;
case TYPE_INT32:
case TYPE_FIXED32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_UINT32:
case TYPE_BOOL:
sb.append(value);
break;
case TYPE_STRING:
appendQuotedString(sb, value);
break;
case TYPE_ENUM:
sb.append(scope.find(fdp.getTypeName()).
children.get(value).fullName);
break;
case TYPE_BYTES:
sb.append("stringToByteArray(");
sb.append("\"");
sb.append(value);
sb.append("\")");
break;
default:
throw new IllegalArgumentException();
}
}
private static void appendLowerCamelCase(StringBuilder sb, String s) {
if (Arrays.binarySearch(ACTIONSCRIPT_KEYWORDS, s) >= 0) {
sb.append("__");
}
sb.append(Character.toLowerCase(s.charAt(0)));
boolean upper = false;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (upper) {
if (Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
upper = false;
continue;
} else {
sb.append('_');
}
}
upper = c == '_';
if (!upper) {
sb.append(c);
}
}
}
private static void appendUpperCamelCase(StringBuilder sb, String s) {
sb.append(Character.toUpperCase(s.charAt(0)));
boolean upper = false;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (upper) {
if (Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
upper = false;
continue;
} else {
sb.append('_');
}
}
upper = c == '_';
if (!upper) {
sb.append(c);
}
}
}
private static void writeMessage(Scope<DescriptorProto> scope,
StringBuilder content, StringBuilder initializerContent) {
content.append("\timport com.netease.protobuf.*;\n");
content.append("\tuse namespace com.netease.protobuf.used_by_generated_code;\n");
content.append("\timport com.netease.protobuf.fieldDescriptors.*;\n");
content.append("\timport flash.utils.Endian;\n");
content.append("\timport flash.utils.IDataInput;\n");
content.append("\timport flash.utils.IDataOutput;\n");
content.append("\timport flash.utils.IExternalizable;\n");
content.append("\timport flash.errors.IOError;\n");
HashSet<String> importTypes = new HashSet<String>();
for (FieldDescriptorProto efdp : scope.proto.getExtensionList()) {
importTypes.add(scope.find(efdp.getExtendee()).fullName);
if (efdp.getType().equals(FieldDescriptorProto.Type.TYPE_MESSAGE)) {
importTypes.add(scope.find(efdp.getTypeName()).fullName);
}
String importType = getImportType(scope, efdp);
if (importType != null) {
importTypes.add(importType);
}
}
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
String importType = getImportType(scope, fdp);
if (importType != null) {
importTypes.add(importType);
}
}
for (String importType : importTypes) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
content.append("\t// @@protoc_insertion_point(imports)\n\n");
String remoteClassAlias;
if (scope.proto.hasOptions()) {
if (scope.proto.getOptions().hasExtension(Options.as3AmfAlias)) {
remoteClassAlias = scope.proto.getOptions().getExtension(Options.as3AmfAlias);
} else if (scope.proto.getOptions().getExtension(Options.as3AmfAutoAlias)) {
remoteClassAlias = scope.fullName;
} else {
remoteClassAlias = null;
}
if (remoteClassAlias != null) {
content.append("\t[RemoteClass(alias=");
appendQuotedString(content, remoteClassAlias);
content.append(")]\n");
}
if (scope.proto.getOptions().getExtension(Options.as3Bindable)) {
content.append("\t[Bindable]\n");
}
} else {
remoteClassAlias = null;
}
content.append("\t// @@protoc_insertion_point(class_metadata)\n");
content.append("\tpublic dynamic final class ");
content.append(scope.proto.getName());
content.append(" extends com.netease.protobuf.Message");
if (remoteClassAlias != null) {
content.append(" implements flash.utils.IExternalizable {\n");
content.append("\t\tpublic final function writeExternal(output:flash.utils.IDataOutput):void {\n");
content.append("\t\t\twriteDelimitedTo(output);\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic final function readExternal(input:flash.utils.IDataInput):void {\n");
content.append("\t\t\tmergeDelimitedFrom(input);\n");
content.append("\t\t}\n\n");
} else {
content.append(" {\n");
}
if (scope.proto.getExtensionRangeCount() > 0) {
content.append("\t\t[ArrayElementType(\"Function\")]\n");
content.append("\t\tpublic static const extensionReadFunctions:Array = [];\n\n");
}
if (scope.proto.getExtensionCount() > 0) {
initializerContent.append("import ");
initializerContent.append(scope.fullName);
initializerContent.append(";\n");
initializerContent.append("if(!");
initializerContent.append(scope.fullName);
initializerContent.append(") throw new Error();\n");
}
for (FieldDescriptorProto efdp : scope.proto.getExtensionList()) {
if (efdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
String extendee = scope.find(efdp.getExtendee()).fullName;
content.append("\t\t/**\n\t\t * @private\n\t\t */\n");
content.append("\t\tpublic static const ");
content.append(efdp.getName().toUpperCase());
content.append(":");
appendFieldDescriptorClass(content, efdp);
content.append(" = ");
appendFieldDescriptor(content, scope, efdp);
content.append(";\n\n");
if (efdp.hasDefaultValue()) {
content.append("\t\t");
content.append(extendee);
content.append(".prototype[");
content.append(efdp.getName().toUpperCase());
content.append("] = ");
appendDefaultValue(content, scope, efdp);
content.append(";\n\n");
}
appendExtensionReadFunction(content, "\t\t", scope, efdp);
}
int valueTypeCount = 0;
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
content.append("\t\t/**\n\t\t * @private\n\t\t */\n");
content.append("\t\tpublic static const ");
content.append(fdp.getName().toUpperCase());
content.append(":");
appendFieldDescriptorClass(content, fdp);
content.append(" = ");
appendFieldDescriptor(content, scope, fdp);
content.append(";\n\n");
assert(fdp.hasLabel());
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
content.append("\t\tprivate var ");
content.append(fdp.getName());
content.append("$field:");
content.append(getActionScript3Type(scope, fdp));
content.append(";\n\n");
if (isValueType(fdp.getType())) {
final int valueTypeId = valueTypeCount++;
final int valueTypeField = valueTypeId / 32;
final int valueTypeBit = valueTypeId % 32;
if (valueTypeBit == 0) {
content.append("\t\tprivate var hasField$");
content.append(valueTypeField);
content.append(":uint = 0;\n\n");
}
content.append("\t\tpublic function clear");
appendUpperCamelCase(content, fdp.getName());
content.append("():void {\n");
content.append("\t\t\thasField$");
content.append(valueTypeField);
content.append(" &= 0x");
content.append(Integer.toHexString(~(1 << valueTypeBit)));
content.append(";\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = new ");
content.append(getActionScript3Type(scope, fdp));
content.append("();\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function get has");
appendUpperCamelCase(content, fdp.getName());
content.append("():Boolean {\n");
content.append("\t\t\treturn (hasField$");
content.append(valueTypeField);
content.append(" & 0x");
content.append(Integer.toHexString(1 << valueTypeBit));
content.append(") != 0;\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function set ");
appendLowerCamelCase(content, fdp.getName());
content.append("(value:");
content.append(getActionScript3Type(scope, fdp));
content.append("):void {\n");
content.append("\t\t\thasField$");
content.append(valueTypeField);
content.append(" |= 0x");
content.append(Integer.toHexString(1 << valueTypeBit));
content.append(";\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = value;\n");
content.append("\t\t}\n\n");
} else {
content.append("\t\tpublic function clear");
appendUpperCamelCase(content, fdp.getName());
content.append("():void {\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = null;\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function get has");
appendUpperCamelCase(content, fdp.getName());
content.append("():Boolean {\n");
content.append("\t\t\treturn ");
content.append(fdp.getName());
content.append("$field != null;\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function set ");
appendLowerCamelCase(content, fdp.getName());
content.append("(value:");
content.append(getActionScript3Type(scope, fdp));
content.append("):void {\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = value;\n");
content.append("\t\t}\n\n");
}
content.append("\t\tpublic function get ");
appendLowerCamelCase(content, fdp.getName());
content.append("():");
content.append(getActionScript3Type(scope, fdp));
content.append(" {\n");
if (fdp.hasDefaultValue()) {
content.append("\t\t\tif(!has");
appendUpperCamelCase(content, fdp.getName());
content.append(") {\n");
content.append("\t\t\t\treturn ");
appendDefaultValue(content, scope, fdp);
content.append(";\n");
content.append("\t\t\t}\n");
}
content.append("\t\t\treturn ");
content.append(fdp.getName());
content.append("$field;\n");
content.append("\t\t}\n\n");
break;
case LABEL_REQUIRED:
content.append("\t\tpublic var ");
appendLowerCamelCase(content, fdp.getName());
content.append(":");
content.append(getActionScript3Type(scope, fdp));
if (fdp.hasDefaultValue()) {
content.append(" = ");
appendDefaultValue(content, scope, fdp);
}
content.append(";\n\n");
break;
case LABEL_REPEATED:
content.append("\t\t[ArrayElementType(\"");
content.append(getActionScript3Type(scope, fdp));
content.append("\")]\n");
content.append("\t\tpublic var ");
appendLowerCamelCase(content, fdp.getName());
content.append(":Array = [];\n\n");
break;
default:
throw new IllegalArgumentException();
}
}
content.append("\t\t/**\n\t\t * @private\n\t\t */\n\t\toverride com.netease.protobuf.used_by_generated_code final function writeToBuffer(output:com.netease.protobuf.WritingBuffer):void {\n");
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
content.append("\t\t\tif (");
content.append("has");
appendUpperCamelCase(content, fdp.getName());
content.append(") {\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append(", ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append("(output, ");
content.append(fdp.getName());
content.append("$field);\n");
content.append("\t\t\t}\n");
break;
case LABEL_REQUIRED:
content.append("\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append(", ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\tcom.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append("(output, this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
break;
case LABEL_REPEATED:
if (fdp.hasOptions() && fdp.getOptions().getPacked()) {
content.append("\t\t\tif (this.");
appendLowerCamelCase(content, fdp.getName());
content.append(" != null && this.");
appendLowerCamelCase(content, fdp.getName());
content.append(".length > 0) {\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.LENGTH_DELIMITED, ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writePackedRepeated(output, com.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append(", this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
content.append("\t\t\t}\n");
} else {
content.append("\t\t\tfor (var ");
appendLowerCamelCase(content, fdp.getName());
content.append("$index:uint = 0; ");
appendLowerCamelCase(content, fdp.getName());
content.append("$index < this.");
appendLowerCamelCase(content, fdp.getName());
content.append(".length; ++");
appendLowerCamelCase(content, fdp.getName());
content.append("$index) {\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append(", ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append("(output, this.");
appendLowerCamelCase(content, fdp.getName());
content.append("[");
appendLowerCamelCase(content, fdp.getName());
content.append("$index]);\n");
content.append("\t\t\t}\n");
}
break;
}
}
content.append("\t\t\tfor (var fieldKey:* in this) {\n");
if (scope.proto.getExtensionRangeCount() > 0) {
content.append("\t\t\t\tsuper.writeExtensionOrUnknown(output, fieldKey);\n");
} else {
content.append("\t\t\t\tsuper.writeUnknown(output, fieldKey);\n");
}
content.append("\t\t\t}\n");
content.append("\t\t}\n\n");
content.append("\t\t/**\n\t\t * @private\n\t\t */\n");
content.append("\t\toverride com.netease.protobuf.used_by_generated_code final function readFromSlice(input:flash.utils.IDataInput, bytesAfterSlice:uint):void {\n");
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
case LABEL_REQUIRED:
content.append("\t\t\tvar ");
content.append(fdp.getName());
content.append("$count:uint = 0;\n");
break;
}
}
content.append("\t\t\twhile (input.bytesAvailable > bytesAfterSlice) {\n");
content.append("\t\t\t\tvar tag:uint = com.netease.protobuf.ReadUtils.read$TYPE_UINT32(input);\n");
content.append("\t\t\t\tswitch (tag >> 3) {\n");
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
content.append("\t\t\t\tcase ");
content.append(Integer.toString(fdp.getNumber()));
content.append(":\n");
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
case LABEL_REQUIRED:
content.append("\t\t\t\t\tif (");
content.append(fdp.getName());
content.append("$count != 0) {\n");
content.append("\t\t\t\t\t\tthrow new flash.errors.IOError('Bad data format: ");
content.append(scope.proto.getName());
content.append('.');
appendLowerCamelCase(content, fdp.getName());
content.append(" cannot be set twice.');\n");
content.append("\t\t\t\t\t}\n");
content.append("\t\t\t\t\t++");
content.append(fdp.getName());
content.append("$count;\n");
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_MESSAGE) {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(" = new ");
content.append(getActionScript3Type(scope, fdp));
content.append("();\n");
content.append("\t\t\t\t\tcom.netease.protobuf.ReadUtils.read$TYPE_MESSAGE(input, this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
} else {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(" = com.netease.protobuf.ReadUtils.read$");
content.append(fdp.getType().name());
content.append("(input);\n");
}
break;
case LABEL_REPEATED:
switch (fdp.getType()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_BOOL:
case TYPE_INT32:
case TYPE_FIXED32:
case TYPE_UINT32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_INT64:
case TYPE_FIXED64:
case TYPE_UINT64:
case TYPE_SFIXED64:
case TYPE_SINT64:
case TYPE_ENUM:
content.append("\t\t\t\t\tif ((tag & 7) == com.netease.protobuf.WireType.LENGTH_DELIMITED) {\n");
content.append("\t\t\t\t\t\tcom.netease.protobuf.ReadUtils.readPackedRepeated(input, com.netease.protobuf.ReadUtils.read$");
content.append(fdp.getType().name());
content.append(", this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
content.append("\t\t\t\t\t\tbreak;\n");
content.append("\t\t\t\t\t}\n");
}
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_MESSAGE) {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(".push(");
content.append("com.netease.protobuf.ReadUtils.read$TYPE_MESSAGE(input, ");
content.append("new ");
content.append(getActionScript3Type(scope, fdp));
content.append("()));\n");
} else {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(".push(com.netease.protobuf.ReadUtils.read$");
content.append(fdp.getType().name());
content.append("(input));\n");
}
break;
}
content.append("\t\t\t\t\tbreak;\n");
}
content.append("\t\t\t\tdefault:\n");
if (scope.proto.getExtensionRangeCount() > 0) {
content.append("\t\t\t\t\tsuper.readExtensionOrUnknown(extensionReadFunctions, input, tag);\n");
} else {
content.append("\t\t\t\t\tsuper.readUnknown(input, tag);\n");
}
content.append("\t\t\t\t\tbreak;\n");
content.append("\t\t\t\t}\n");
content.append("\t\t\t}\n");
content.append("\t\t}\n\n");
content.append("\t}\n");
}
private static void appendFieldDescriptorClass(StringBuilder content,
FieldDescriptorProto fdp) {
switch (fdp.getLabel()) {
case LABEL_REQUIRED:
case LABEL_OPTIONAL:
break;
case LABEL_REPEATED:
content.append("Repeated");
break;
default:
throw new IllegalArgumentException();
}
content.append("FieldDescriptor$");
content.append(fdp.getType().name());
}
private static void appendFieldDescriptor(StringBuilder content,
Scope<?> scope,
FieldDescriptorProto fdp) {
content.append("new ");
appendFieldDescriptorClass(content, fdp);
content.append("(");
if (scope.parent == null) {
appendQuotedString(content, fdp.getName());
} else {
appendQuotedString(content, scope.fullName + '.' + fdp.getName());
}
content.append(", ");
if (fdp.hasExtendee()) {
if (scope.proto instanceof DescriptorProto) {
appendQuotedString(content, scope.fullName + '/' + fdp.getName().toUpperCase());
} else {
if (scope.parent == null) {
appendQuotedString(content, fdp.getName().toUpperCase());
} else {
appendQuotedString(content, scope.fullName + '.' + fdp.getName().toUpperCase());
}
}
} else {
StringBuilder fieldName = new StringBuilder();
appendLowerCamelCase(fieldName, fdp.getName());
appendQuotedString(content, fieldName.toString());
}
content.append(", (");
switch (fdp.getLabel()) {
case LABEL_REQUIRED:
case LABEL_OPTIONAL:
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
break;
case LABEL_REPEATED:
if (fdp.hasOptions() && fdp.getOptions().getPacked()) {
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.LENGTH_DELIMITED");
} else {
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
}
break;
}
switch (fdp.getType()) {
case TYPE_MESSAGE:
if (scope.proto instanceof DescriptorProto) {
content.append(", function():Class { return ");
content.append(getActionScript3LogicType(scope, fdp));
content.append("; }");
} else {
content.append(", ");
content.append(getActionScript3LogicType(scope, fdp));
}
break;
case TYPE_ENUM:
content.append(", ");
content.append(getActionScript3LogicType(scope, fdp));
break;
}
content.append(")");
}
private static void appendExtensionReadFunction(StringBuilder content,
String tabs,
Scope<?> scope,
FieldDescriptorProto fdp) {
String extendee = scope.find(fdp.getExtendee()).fullName;
switch (fdp.getLabel()) {
case LABEL_REQUIRED:
case LABEL_OPTIONAL:
content.append(tabs);
content.append(extendee);
content.append(".extensionReadFunctions[(");
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append("] = ");
content.append(fdp.getName().toUpperCase());
content.append(".read;\n\n");
break;
case LABEL_REPEATED:
content.append(tabs);
content.append(extendee);
content.append(".extensionReadFunctions[(");
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append("] = ");
content.append(fdp.getName().toUpperCase());
content.append(".readNonPacked;\n\n");
switch (fdp.getType()) {
case TYPE_MESSAGE:
case TYPE_BYTES:
case TYPE_STRING:
break;
default:
content.append(tabs);
content.append(extendee);
content.append(".extensionReadFunctions[(");
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.LENGTH_DELIMITED] = ");
content.append(fdp.getName().toUpperCase());
content.append(".readPacked;\n\n");
break;
}
break;
}
}
private static void writeExtension(Scope<FieldDescriptorProto> scope,
StringBuilder content, StringBuilder initializerContent) {
initializerContent.append("import ");
initializerContent.append(scope.fullName);
initializerContent.append(";\n");
initializerContent.append("if(!");
initializerContent.append(scope.fullName);
initializerContent.append(") throw new Error;\n");
content.append("\timport com.netease.protobuf.*;\n");
content.append("\timport com.netease.protobuf.fieldDescriptors.*;\n");
String importType = getImportType(scope.parent, scope.proto);
if (importType != null) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
String extendee = scope.parent.find(scope.proto.getExtendee()).fullName;
content.append("\timport ");
content.append(extendee);
content.append(";\n");
content.append("\t// @@protoc_insertion_point(imports)\n\n");
content.append("\t// @@protoc_insertion_point(constant_metadata)\n");
content.append("\t/**\n\t * @private\n\t */\n");
content.append("\tpublic const ");
content.append(scope.proto.getName().toUpperCase());
content.append(":");
appendFieldDescriptorClass(content, scope.proto);
content.append(" = ");
appendFieldDescriptor(content, scope.parent, scope.proto);
content.append(";\n\n");
if (scope.proto.hasDefaultValue()) {
content.append("\t");
content.append(extendee);
content.append(".prototype[");
content.append(scope.proto.getName().toUpperCase());
content.append("] = ");
appendDefaultValue(content, scope.parent, scope.proto);
content.append(";\n\n");
}
appendExtensionReadFunction(content, "\t", scope.parent, scope.proto);
}
private static void writeEnum(Scope<EnumDescriptorProto> scope,
StringBuilder content) {
content.append("\tpublic final class ");
content.append(scope.proto.getName());
content.append(" {\n");
for (EnumValueDescriptorProto evdp : scope.proto.getValueList()) {
content.append("\t\tpublic static const ");
content.append(evdp.getName());
content.append(":int = ");
content.append(evdp.getNumber());
content.append(";\n");
}
content.append("\t}\n");
}
@SuppressWarnings("unchecked")
private static void writeFile(Scope<?> scope, StringBuilder content,
StringBuilder initializerContent) {
content.append("package ");
content.append(scope.parent.fullName);
content.append(" {\n");
if (scope.proto instanceof DescriptorProto) {
writeMessage((Scope<DescriptorProto>)scope, content,
initializerContent);
} else if (scope.proto instanceof EnumDescriptorProto) {
writeEnum((Scope<EnumDescriptorProto>)scope, content);
} else if (scope.proto instanceof FieldDescriptorProto) {
Scope<FieldDescriptorProto> fdpScope =
(Scope<FieldDescriptorProto>)scope;
if (fdpScope.proto.getType() ==
FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
} else {
writeExtension(fdpScope, content, initializerContent);
}
} else {
throw new IllegalArgumentException();
}
content.append("}\n");
}
@SuppressWarnings("unchecked")
private static void writeFiles(Scope<?> root,
CodeGeneratorResponse.Builder responseBuilder,
StringBuilder initializerContent) {
for (Map.Entry<String, Scope<?>> entry : root.children.entrySet()) {
Scope<?> scope = entry.getValue();
if (scope.export) {
if (scope.proto instanceof ServiceDescriptorProto) {
ServiceDescriptorProto serviceProto = (ServiceDescriptorProto)scope.proto;
if (serviceProto.getOptions().getExtension(Options.as3ClientSideService) ||
serviceProto.getOptions().getExtension(Options.as3ServerSideService)) {
StringBuilder classContent = new StringBuilder();
writeServiceClass((Scope<ServiceDescriptorProto>)scope, classContent);
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName(scope.fullName.replace('.', '/') + ".as").
setContent(classContent.toString()).
build()
);
StringBuilder interfaceContent = new StringBuilder();
writeServiceInterface((Scope<ServiceDescriptorProto>)scope, interfaceContent);
String[] servicePath = scope.fullName.split("\\.");
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < servicePath.length - 1; i++) {
sb.append(servicePath[i]);
sb.append('/');
}
sb.append('I');
sb.append(servicePath[i]);
sb.append(".as");
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName(sb.toString()).
setContent(interfaceContent.toString()).
build()
);
}
}
else
{
StringBuilder content = new StringBuilder();
writeFile(scope, content, initializerContent);
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName(scope.fullName.replace('.', '/') + ".as").
setContent(content.toString()).
build()
);
}
}
writeFiles(scope, responseBuilder, initializerContent);
}
}
private static void writeFiles(Scope<?> root,
CodeGeneratorResponse.Builder responseBuilder) {
StringBuilder initializerContent = new StringBuilder();
initializerContent.append("{\n");
writeFiles(root, responseBuilder, initializerContent);
initializerContent.append("}\n");
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName("initializer.as.inc").
setContent(initializerContent.toString()).
build()
);
}
private static void writeServiceClass(Scope<ServiceDescriptorProto> scope,
StringBuilder content) {
content.append("package ");
content.append(scope.parent.fullName);
content.append(" {\n");
HashSet<String> importTypes = new HashSet<String>();
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
importTypes.add(scope.find(mdp.getInputType()).fullName);
if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) {
importTypes.add(scope.find(mdp.getOutputType()).fullName);
}
}
for (String importType : importTypes) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
content.append("\timport google.protobuf.*;\n");
content.append("\timport flash.utils.*;\n");
content.append("\timport com.netease.protobuf.*;\n");
content.append("\t// @@protoc_insertion_point(imports)\n\n");
content.append("\tpublic final class ");
content.append(scope.proto.getName());
if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) {
content.append(" implements ");
if (scope.parent.isRoot()) {
content.append("I");
} else {
content.append(scope.parent.fullName);
content.append(".I");
}
content.append(scope.proto.getName());
}
content.append(" {\n");
if (scope.proto.hasOptions()) {
content.append("\t\tpublic static const OPTIONS_BYTES:flash.utils.ByteArray = com.netease.protobuf.stringToByteArray(\"");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
scope.proto.getOptions().writeTo(buffer);
} catch (IOException e) {
throw new IllegalStateException("ByteArrayOutputStream should not throw IOException!", e);
}
for (byte b : buffer.toByteArray()) {
content.append("\\x");
content.append(Character.forDigit((b & 0xF0) >>> 4, 16));
content.append(Character.forDigit(b & 0x0F, 16));
}
content.append("\");\n\n");
content.append("\t\tpublic static function getOptions():google.protobuf.ServiceOptions\n");
content.append("\t\t{\n");
content.append("\t\t\tOPTIONS_BYTES.position = 0;\n");
content.append("\t\t\tconst options:google.protobuf.ServiceOptions = new google.protobuf.ServiceOptions();\n");
content.append("\t\t\toptions.mergeFrom(OPTIONS_BYTES);\n\n");
content.append("\t\t\treturn options;\n");
content.append("\t\t}\n\n");
}
boolean hasMethodOptions = false;
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
if (mdp.hasOptions()) {
if (!hasMethodOptions) {
hasMethodOptions = true;
content.append("\t\tpublic static const OPTIONS_BYTES_BY_METHOD_NAME:Object =\n");
content.append("\t\t{\n");
} else {
content.append(",\n");
}
content.append("\t\t\t\"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\" : stringToByteArray(\"");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
mdp.getOptions().writeTo(buffer);
} catch (IOException e) {
throw new IllegalStateException("ByteArrayOutputStream should not throw IOException!", e);
}
for (byte b : buffer.toByteArray()) {
content.append("\\x");
content.append(Character.forDigit((b & 0xF0) >>> 4, 16));
content.append(Character.forDigit(b & 0x0F, 16));
}
content.append("\")");
}
}
if (hasMethodOptions) {
content.append("\n\t\t};\n\n");
}
if (scope.proto.getOptions().getExtension(Options.as3ServerSideService)) {
content.append("\t\tpublic static const REQUEST_CLASSES_BY_METHOD_NAME:Object =\n");
content.append("\t\t{\n");
boolean comma = false;
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
if (comma) {
content.append(",\n");
} else {
comma = true;
}
content.append("\t\t\t\"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\" : ");
content.append(scope.find(mdp.getInputType()).fullName);
}
content.append("\n\t\t};\n\n");
content.append("\t\tpublic static function callMethod(service:");
if (scope.parent.isRoot()) {
content.append("I");
} else {
content.append(scope.parent.fullName);
content.append(".I");
}
content.append(scope.proto.getName());
content.append(", methodName:String, request:com.netease.protobuf.Message, responseHandler:Function):void {\n");
content.append("\t\t\tswitch (methodName) {\n");
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
content.append("\t\t\t\tcase \"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\":\n");
content.append("\t\t\t\t{\n");
content.append("\t\t\t\t\tservice.");
appendLowerCamelCase(content, mdp.getName());
content.append("(");
content.append(scope.find(mdp.getInputType()).fullName);
content.append("(request), responseHandler);\n");
content.append("\t\t\t\t\tbreak;\n");
content.append("\t\t\t\t}\n");
}
content.append("\t\t\t}\n");
content.append("\t\t}\n\n");
}
if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) {
content.append("\t\tpublic var sendFunction:Function;\n\n");
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
content.append("\t\tpublic function ");
appendLowerCamelCase(content, mdp.getName());
content.append("(request:");
content.append(scope.find(mdp.getInputType()).fullName);
content.append(", responseHandler:Function):void {\n");
content.append("\t\t\tsendFunction(\"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\", request, responseHandler, ");
content.append(scope.find(mdp.getOutputType()).fullName);
content.append(");\n");
content.append("\t\t}\n\n");
}
}
content.append("\t}\n");
content.append("}\n");
}
private static void writeServiceInterface(
Scope<ServiceDescriptorProto> scope,
StringBuilder content) {
content.append("package ");
content.append(scope.parent.fullName);
content.append(" {\n");
HashSet<String> importTypes = new HashSet<String>();
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
importTypes.add(scope.find(mdp.getInputType()).fullName);
}
for (String importType : importTypes) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
content.append("\t// @@protoc_insertion_point(imports)\n\n");
content.append("\tpublic interface I");
content.append(scope.proto.getName());
content.append(" {\n\n");
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
content.append("\t\tfunction ");
appendLowerCamelCase(content, mdp.getName());
content.append("(input:");
content.append(scope.find(mdp.getInputType()).fullName);
content.append(", done:Function):void;\n\n");
}
content.append("\t}\n");
content.append("}\n");
}
public static void main(String[] args) throws IOException {
ExtensionRegistry registry = ExtensionRegistry.newInstance();
Options.registerAllExtensions(registry);
CodeGeneratorRequest request = CodeGeneratorRequest.
parseFrom(System.in, registry);
CodeGeneratorResponse response;
try {
Scope<Object> root = buildScopeTree(request);
CodeGeneratorResponse.Builder responseBuilder =
CodeGeneratorResponse.newBuilder();
writeFiles(root, responseBuilder);
response = responseBuilder.build();
} catch (Exception e) {
// 出错,报告给 protoc ,然后退出
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
CodeGeneratorResponse.newBuilder().setError(sw.toString()).
build().writeTo(System.out);
System.out.flush();
return;
}
response.writeTo(System.out);
System.out.flush();
}
}
|
118194141-test
|
compiler/com/netease/protocGenAs3/Main.java
|
Java
|
bsd
| 48,128
|
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.test {
import google.protobuf.FileDescriptorSet;
import protobuf_unittest.*
import protobuf_unittest.TestAllTypes.*
import test.*
import flash.display.*
import flash.utils.*
import flash.system.*
import com.netease.protobuf.*
public class TestAll {
private static function assert(b:Boolean,
errorMessage:String = "Assertion failed.",
errorId:int = 0):void {
if (!b) {
throw new Error(errorMessage, errorId)
}
}
private static function assertSame(l:*, r:*, name:String = ""):void {
if (typeof(l) == "object") {
assert(getQualifiedClassName(l) ==
getQualifiedClassName(r))
if (l is Array || l is ByteArray) {
assertSame(l.length, r.length, name + ".length")
for (var i:int = 0; i < l.length; i++) {
assertSame(l[i], r[i], name + "[" + i + "]")
}
} else {
var k:*
for(k in l) {
assertSame(l[k], r[k], name + "[" + k + "]")
}
for(k in r) {
assertSame(l[k], r[k], name + "[" + k + "]")
}
const description:XML = describeType(l)
for each(var getter:XML in description..accessor.(@access != "writeonly")) {
assertSame(l[getter.@name], r[getter.@name], name + "." + getter.@name)
}
for each(var field:XML in description..variable) {
assertSame(l[field.@name], r[field.@name], name + "." + field.@name)
}
}
} else {
assert(l === r || (isNaN(l) && isNaN(r)), name + " not equal.")
}
}
private static const HEX_CHARS:String = "0123456789ABCDEF"
private static function testAmf(input:*):void {
const ba:ByteArray = new ByteArray
ba.writeObject(input)
var s:String = ""
for (var i:uint = 0; i < ba.length; i++) {
s += HEX_CHARS.charAt(ba[i] / 16)
s += HEX_CHARS.charAt(ba[i] % 16)
s += " "
}
trace(input)
trace(s)
ba.position = 0
const output:* = ba.readObject()
assertSame(input, output)
}
private static function testText(input:Message):void {
const text:String =
com.netease.protobuf.TextFormat.printToString(input, false)
const output:Message =
new (getDefinitionByName(getQualifiedClassName(input)))
com.netease.protobuf.TextFormat.mergeFromString(text, output)
trace("input:", input, "output:", output, "text:", text)
assertSame(input, output)
}
private static function test(input:Message):void {
const ba:ByteArray = new ByteArray
input.writeTo(ba)
var s:String = ""
for (var i:uint = 0; i < ba.length; i++) {
s += HEX_CHARS.charAt(ba[i] / 16)
s += HEX_CHARS.charAt(ba[i] % 16)
s += " "
}
ba.position = 0
const output:Message = new (getDefinitionByName(
getQualifiedClassName(input)))
output.mergeFrom(ba)
assertSame(input, output)
}
public static function run(haxeTest:Boolean = false):void {
const int64:Int64 = new Int64(0x12345678, 0x91abcde1)
assertSame(int64.toString(), "-7950034350635723144")
assertSame(Int64.parseInt64(int64.toString()), int64)
const int64_2:Int64 = new Int64(0x12345678, 0xb)
assertSame(int64_2.toString(), "47550060152")
assertSame(Int64.parseInt64(int64_2.toString()), int64_2)
const int64_3:Int64 = new Int64(0x12345678, 0xabcdef12)
assertSame(int64_3.toString(), "-6066930262104320392")
assertSame(Int64.parseInt64(int64_3.toString()), int64_3)
const int64_4:Int64 = new Int64(0x12345678, 0xbb)
assertSame(int64_4.toString(), "803464304248")
assertSame(Int64.parseInt64(int64_4.toString()), int64_4)
const int64_5:Int64 = new Int64(0, 0)
assertSame(int64_5.toString(), "0")
assertSame(Int64.parseInt64(int64_5.toString()), int64_5)
const int64_6:Int64 = Int64.fromNumber(-123234)
assertSame(int64_6.toNumber(), -123234)
assertSame(int64_6.toString(), "-123234")
assertSame(Int64.parseInt64(int64_6.toString()), int64_6)
const int64_7:Int64 = Int64.fromNumber(-184942424123234000)
assertSame(int64_7.toNumber(), -184942424123233984)
assertSame(int64_7.toString(), "-184942424123233984")
assertSame(Int64.parseInt64(int64_7.toString()), int64_7)
const int64_8:Int64 = Int64.fromNumber(-1494242414000)
assertSame(int64_8.toNumber(), -1494242414000)
assertSame(int64_8.toString(), "-1494242414000")
assertSame(Int64.parseInt64(int64_8.toString()), int64_8)
const int64_10:Int64 = Int64.fromNumber(-1024)
assertSame(int64_10.toNumber(), -1024)
assertSame(int64_10.toString(), "-1024")
assertSame(Int64.parseInt64(int64_10.toString()), int64_10)
assertSame(Int64.parseInt64("-0x400"), int64_10)
const int64_11:Int64 = Int64.fromNumber(0)
assertSame(int64_11.toNumber(), 0)
assertSame(int64_11.toString(), "0")
assertSame(Int64.parseInt64(int64_11.toString()), int64_11)
assertSame(Int64.parseInt64("0"), int64_11)
assertSame(Int64.parseInt64("0x0"), int64_11)
assertSame(Int64.parseInt64("-0"), int64_11)
assertSame(Int64.parseInt64("-0x0"), int64_11)
const int64_9:Int64 = Int64.fromNumber(-1)
assertSame(int64_9.toNumber(), -1)
assertSame(int64_9.toString(), "-1")
assertSame(Int64.parseInt64(int64_9.toString()), int64_9)
assertSame(Int64.parseInt64("-0x1"), int64_9)
assertSame(Int64.parseInt64("-01"), int64_9)
const int64_12:Int64 = new Int64(0, -1)
assertSame(int64_12.toNumber(), -4294967296.0)
assertSame(int64_12.toString(), "-4294967296")
assertSame(Int64.parseInt64(int64_12.toString()), int64_12)
assertSame(Int64.parseInt64("-0x100000000"), int64_12)
assertSame(Int64.parseInt64("0xFFFFFFFF00000000"), int64_12)
const int64_13:Int64 = Int64.parseInt64("0xFFFFFFF000000000")
assertSame(int64_13.toNumber(), -68719476736.0)
assertSame(int64_13.toString(), "-68719476736")
assertSame(Int64.parseInt64(int64_13.toString()), int64_13)
assertSame(Int64.parseInt64("-68719476736"), int64_13)
const int64_14:Int64 = Int64.parseInt64("0xFFFFFFFFF0000000")
assertSame(int64_14.toNumber(), -268435456.0)
assertSame(int64_14.toString(), "-268435456")
assertSame(Int64.parseInt64(int64_14.toString()), int64_14)
assertSame(Int64.parseInt64("-268435456"), int64_14)
const uint64_9:UInt64 = UInt64.fromNumber(123234)
assertSame(uint64_9.toNumber(), 123234)
assertSame(uint64_9.toString(), "123234")
assertSame(UInt64.parseUInt64(uint64_9.toString()), uint64_9)
assertSame(UInt64.parseUInt64("0x" + uint64_9.toString(16)), uint64_9)
const uint64_10:UInt64 = UInt64.fromNumber(184942424123234000)
assertSame(uint64_10.toNumber(), 184942424123233984)
assertSame(uint64_10.toString(), "184942424123233984")
assertSame(UInt64.parseUInt64(uint64_10.toString()), uint64_10)
const uint64_11:UInt64 = UInt64.fromNumber(1494242414000)
assertSame(uint64_11.toNumber(), 1494242414000)
assertSame(uint64_11.toString(), "1494242414000")
assertSame(UInt64.parseUInt64(uint64_11.toString()), uint64_11)
const uint64:UInt64 = new UInt64(0x12345678, 0)
assertSame(uint64.toString(), "305419896")
assertSame(UInt64.parseUInt64(uint64.toString()), uint64)
const uint64_2:UInt64 = new UInt64(0x12345678, 0xb)
assertSame(uint64_2.toString(), "47550060152")
assertSame(UInt64.parseUInt64(uint64_2.toString()), uint64_2)
const uint64_3:UInt64 = new UInt64(0x12345678, 0xabcdef12)
assertSame(uint64_3.toString(), "12379813811605231224")
assertSame(UInt64.parseUInt64(uint64_3.toString()), uint64_3)
const uint64_4:UInt64 = new UInt64(0x12345678, 0xbb)
assertSame(uint64_4.toString(), "803464304248")
assertSame(UInt64.parseUInt64(uint64_4.toString()), uint64_4)
const uint64_5:UInt64 = new UInt64(0, 0)
assertSame(uint64_5.toString(), "0")
assertSame(UInt64.parseUInt64(uint64_5.toString()), uint64_5)
const uint64_6:UInt64 = UInt64.fromNumber(123234)
assertSame(uint64_6.toNumber(), 123234)
assertSame(uint64_6.toString(), "123234")
assertSame(UInt64.parseUInt64(uint64_6.toString()), uint64_6)
const uint64_7:UInt64 = UInt64.fromNumber(184942424123234000)
assertSame(uint64_7.toNumber(), 184942424123233984)
assertSame(uint64_7.toString(), "184942424123233984")
assertSame(UInt64.parseUInt64(uint64_7.toString()), uint64_7)
const uint64_8:UInt64 = UInt64.fromNumber(1494242414000)
assertSame(uint64_8.toNumber(), 1494242414000)
assertSame(uint64_8.toString(), "1494242414000")
assertSame(UInt64.parseUInt64(uint64_8.toString()), uint64_8)
const t0:TestAllTypes = new TestAllTypes
t0[1500938] = stringToByteArray('\n')
test(t0)
testText(t0)
const t1:TestPackedTypes = new TestPackedTypes
t1.packedDouble.push(1.23424353, 2.12)
t1.packedEnum.push(ForeignEnum.FOREIGN_BAZ, ForeignEnum.FOREIGN_FOO,
ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR)
test(t1)
testText(t1)
const t2:TestPackedExtensions = new TestPackedExtensions
t2[PACKED_DOUBLE_EXTENSION] = [324.234, 1.23424353, 2.12]
t2[PACKED_ENUM_EXTENSION] =[ForeignEnum.FOREIGN_BAZ,
ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_FOO]
test(t2)
testText(t2)
const t3:TestAllTypes = new TestAllTypes
t3.optionalString = "111foo"
t3.defaultNestedEnum = NestedEnum.FOO
t3.repeatedNestedMessage.push(new NestedMessage)
t3.repeatedNestedMessage.push(new NestedMessage)
t3.repeatedNestedMessage[1].bb = 123
t3.optionalInt32 = -23412413
t3.optionalDouble = 123.456
t3.repeatedNestedEnum.push(NestedEnum.FOO)
t3.repeatedNestedEnum.push(NestedEnum.BAR)
t3.optionalNestedMessage = new NestedMessage
t3.optionalNestedMessage.bb = 234
t3.optionalSint32 = -3
t3.optionalSint64 = new Int64(199999999, 199999999)
test(t3)
testText(t3)
const t4:TestPackedTypes = new TestPackedTypes
t4.packedDouble.push(1)
test(t4)
testText(t4)
const t5:TestAllTypes = new TestAllTypes
t5.optionalSint32 = -199999999
test(t5)
testText(t5)
const t6:TestAllTypes = new TestAllTypes
t6.optionalInt64 = new Int64(uint(-185754567), -198741265)
test(t6)
testText(t6)
const t7:TestAllTypes = new TestAllTypes
const s64:Int64 = new Int64(uint(-171754567), -198741265)
t7.optionalSint64 = s64
t7.optionalInt64 = new Int64(ZigZag.encode64low(s64.low, s64.high),
ZigZag.encode64high(s64.low, s64.high))
t7.optionalInt32 = -1
t7[41192] = UInt64.parseUInt64("12343245732475923") // Unknown Varint
t7[631669] = 12345325 // Unknown Fixed32
t7[631677] = [234, 234, 123222, 12345325] // Unknown Fixed32
t7[1500930] = stringToByteArray("Hello\u00C4\u00C3xxx") // Unknown Length Delimited
t7[1500938] = [stringToByteArray("Hello"), stringToByteArray("World")] // Unknown Length Delimited
testText(t7)
test(t7)
const t9:TestAllTypes = new TestAllTypes
t9.optionalSint64 = new Int64(uint(-171754567), -198741265)
test(t9)
testText(t9)
const t10:AAA = new AAA
assertSame(t10[DDD], "dream")
t10.s = "xxxx"
t10[DDD] = "love"
test(t10)
testText(t10)
if (haxeTest) {
import flash.net.registerClassAlias
registerClassAlias("中文名", AAA)
registerClassAlias("com.dongxiguo.Foo", BBB)
}
testAmf(t10)
const t11:BBB = new BBB
t11.aaa = new AAA
t11.aaa.s = "1234xxx"
t11.aaa.bbb = [ new BBB ]
t11.i = 1234
test(t11)
testText(t11)
testAmf(t11)
testAmf([t10, t11, t10])
const t12:TestAllExtensions = new TestAllExtensions
t12[REPEATED_STRING_EXTENSION] = ["aaaa", "bbb"]
test(t12)
testText(t12);
[Embed(source = "../../../../../unittest.bin",
mimeType="application/octet-stream")]
const UNITTEST_BIN:Class
const descriptors:FileDescriptorSet = new FileDescriptorSet
descriptors.mergeFrom(new UNITTEST_BIN)
test(descriptors)
testText(descriptors)
const t13:CCC = new CCC
t13.ccc = "我爱北京天安门"
testText(t13)
trace("All tests pass.")
fscommand("quit")
}
}
}
// vim: ts=4 sw=4
|
118194141-test
|
test/com/netease/protobuf/test/TestAll.as
|
AngelScript
|
bsd
| 12,126
|
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.test;
class HaxeTest
{
static function main():Void
{
TestAll.run(true);
}
}
|
118194141-test
|
test/com/netease/protobuf/test/HaxeTest.hx
|
Haxe
|
bsd
| 366
|
# Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
#
# Author: Yang Bo (pop.atry@gmail.com)
#
# Use, modification and distribution are subject to the "New BSD License"
# as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
include config.mk
ifeq ($(OS), Windows_NT)
PROTOC_GEN_AS3=dist\\protoc-gen-as3$(BAT)
else
PROTOC_GEN_AS3=dist/protoc-gen-as3$(BAT)
endif
ALL=dist/protoc-gen-as3 dist/protoc-gen-as3.bat dist/LICENSE \
dist/protobuf.swc dist/README dist/options.proto \
dist/protoc-gen-as3.jar dist/protobuf-java-$(PROTOBUF_VERSION).jar \
dist/run.n dist/haxelib.xml
all: $(ALL)
dist/haxelib.xml: haxelib.xml
install --mode=644 $< $@
dist/run.n: hx/com/dongxiguo/protobuf/Run.hx
haxe -cp hx -lib haxelib-run -main com.dongxiguo.protobuf.Run -neko $@
classes/com/netease/protocGenAs3/Main.class: \
plugin.proto.java/google/protobuf/compiler/Plugin.java \
options.proto.java/com \
compiler/com/netease/protocGenAs3/Main.java \
$(PROTOBUF_DIR)/java/target/protobuf-java-$(PROTOBUF_VERSION).jar \
| classes
$(JAVAC) -source 1.5 -target 1.5 -encoding UTF-8 -d classes \
-classpath "$(PROTOBUF_DIR)/java/target/protobuf-java-$(PROTOBUF_VERSION).jar" \
-sourcepath "plugin.proto.java$(PATH_SEPARATOR)compiler$(PATH_SEPARATOR)options.proto.java" \
compiler/com/netease/protocGenAs3/Main.java
plugin.proto.java/google/protobuf/compiler/Plugin.java: \
$(PROTOCDEPS) | plugin.proto.java
$(PROTOC) \
"--proto_path=$(PROTOBUF_DIR)/src" --java_out=plugin.proto.java \
"$(PROTOBUF_DIR)/src/google/protobuf/compiler/plugin.proto"
dist.tar.gz: $(ALL)
tar -acf dist.tar.gz -C dist .
release.zip: $(ALL)
zip --junk-paths --filesync $@ $^
dist/LICENSE: LICENSE | dist
install --mode=644 $< $@
dist/README: README | dist
install --mode=644 $< $@
dist/options.proto: options.proto | dist
install --mode=644 $< $@
dist/protoc-gen-as3: dist/protoc-gen-as3.jar dist/protobuf-java-$(PROTOBUF_VERSION).jar \
| dist
(echo '#!/bin/sh';\
echo 'cd "`dirname "$$0"`" && java -jar protoc-gen-as3.jar') > $@
chmod +x $@
dist/protoc-gen-as3.bat: dist/protoc-gen-as3.jar dist/protobuf-java-$(PROTOBUF_VERSION).jar \
| dist
(echo '@cd %~dp0';\
echo '@java -jar protoc-gen-as3.jar') > $@
chmod +x $@
COMMA=,
dist/protobuf.swc: $(wildcard as3/com/netease/protobuf/*/*.as as3/com/netease/protobuf/*.as) descriptor.proto.as3/google | dist
$(COMPC) -target-player=10 \
-source-path+=as3,descriptor.proto.as3 \
-include-sources+=as3 \
-output=$@
doc: \
$(wildcard as3/com/netease/protobuf/*/*.as as3/com/netease/protobuf/*.as) \
descriptor.proto.as3/google \
| dist
$(ASDOC) -target-player=10 \
--doc-sources+=as3 \
--source-path+=descriptor.proto.as3 \
-output=$@ \
-exclude-sources+=as3/com/netease/protobuf/CustomOption.as
doc.tar.gz: doc
tar -acf $@ $<
MANIFEST.MF:
echo Class-Path: protobuf-java-$(PROTOBUF_VERSION).jar > $@
dist/protoc-gen-as3.jar: classes/com/netease/protocGenAs3/Main.class \
MANIFEST.MF | dist
$(JAR) cemf com/netease/protocGenAs3/Main MANIFEST.MF $@ -C classes .
dist/protobuf-java-$(PROTOBUF_VERSION).jar: \
$(PROTOBUF_DIR)/java/target/protobuf-java-$(PROTOBUF_VERSION).jar \
| dist
cp $< $@
options.proto.java descriptor.proto.as3 classes plugin.proto.java unittest.proto.as3 dist:
mkdir $@
ifndef PROTOC
PROTOC=$(PROTOBUF_DIR)/src/protoc$(EXE)
PROTOCDEPS=$(PROTOC)
$(PROTOC): $(PROTOBUF_DIR)/Makefile
cd $(PROTOBUF_DIR) && $(MAKE)
$(PROTOBUF_DIR)/Makefile: $(PROTOBUF_DIR)/configure
cd $(PROTOBUF_DIR) && ./configure
$(PROTOBUF_DIR)/configure:
cd $(PROTOBUF_DIR) && ./autogen.sh
$(PROTOBUF_DIR)/java/target/protobuf-java-$(PROTOBUF_VERSION).jar: \
$(PROTOBUF_DIR)/src \
$(PROTOC)
cd $(PROTOBUF_DIR)/java && $(MVN) package
endif
clean:
$(RM) -r release.zip doc doc.tar.gz dist dist.tar.gz classes unittest.proto.as3 descriptor.proto.as3 plugin.proto.java test.swc test.swf options.proto.java
test: test.swf
(sleep 1s; echo c; sleep 3s; echo c; sleep 1s) | $(FDB) $<
haxe-test: haxe-test.swf
(sleep 1s; echo c; sleep 1s; echo c; sleep 1s) | $(FDB) $<
haxe-test.swc: test/com/netease/protobuf/test/TestAll.as \
dist/protobuf.swc test.swc descriptor.proto.as3/google unittest.bin
$(RM) -r $@
$(COMPC) -target-player=10 \
-directory -include-sources+=$< \
-source-path+=descriptor.proto.as3 \
-library-path+=test.swc,dist/protobuf.swc \
-output=$@
haxe-test.swf: haxe-test.swc test/com/netease/protobuf/test/HaxeTest.hx test.swf
$(HAXE) -cp test -main com.netease.protobuf.test.HaxeTest \
-debug -D fdb --macro 'patchTypes("haxe-test.patch")' \
-swf $@ -swf-version 10 -swf-lib $</library.swf
test.swf: test.swc test/com/netease/protobuf/test/TestAll.as \
test/com/netease/protobuf/test/Test.mxml dist/protobuf.swc \
descriptor.proto.as3/google unittest.bin
$(MXMLC) -target-player=10 \
-library-path+=test.swc,dist/protobuf.swc -output=$@ \
-source-path+=descriptor.proto.as3,test test/com/netease/protobuf/test/Test.mxml -debug
test.swc: unittest.proto.as3/protobuf_unittest dist/protobuf.swc
$(COMPC) -target-player=10 \
-include-sources+=unittest.proto.as3 \
-external-library-path+=dist/protobuf.swc -output=$@
options.proto.java/com: \
options.proto \
$(PROTOCDEPS) \
| options.proto.java
$(PROTOC) \
--proto_path=. \
"--proto_path=$(PROTOBUF_DIR)/src" \
--java_out=options.proto.java $<
touch $@
descriptor.proto.as3/google: \
$(PROTOCDEPS) \
dist/protoc-gen-as3$(BAT) \
| descriptor.proto.as3
$(PROTOC) \
--plugin=protoc-gen-as3=$(PROTOC_GEN_AS3) \
"--proto_path=$(PROTOBUF_DIR)/src" \
--as3_out=descriptor.proto.as3 \
"$(PROTOBUF_DIR)/src/google/protobuf/descriptor.proto"
touch $@
unittest.bin: $(PROTOCDEPS) $(wildcard test/*.proto)
$(PROTOC) \
--proto_path=test --proto_path=. \
"--proto_path=$(PROTOBUF_DIR)/src" \
--descriptor_set_out=$@ \
$(PROTOBUF_DIR)/src/google/protobuf/unittest.proto \
$(PROTOBUF_DIR)/src/google/protobuf/unittest_import.proto \
test/*.proto
unittest.proto.as3/protobuf_unittest: \
$(PROTOCDEPS) \
dist/protoc-gen-as3$(BAT) \
$(wildcard test/*.proto) \
| unittest.proto.as3
$(PROTOC) \
--plugin=protoc-gen-as3=$(PROTOC_GEN_AS3) \
--proto_path=test --proto_path=. \
"--proto_path=$(PROTOBUF_DIR)/src" \
--as3_out=unittest.proto.as3 \
$(PROTOBUF_DIR)/src/google/protobuf/unittest.proto \
$(PROTOBUF_DIR)/src/google/protobuf/unittest_import.proto \
test/*.proto
touch $@
install: release.zip
haxelib test $<
.PHONY: plugin all clean test doc install
|
118194141-test
|
Makefile
|
Makefile
|
bsd
| 6,458
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
public final class Int64 extends Binary64 {
public final function set high(value:int):void {
internalHigh = value
}
public final function get high():int {
return internalHigh
}
public function Int64(low:uint = 0, high:int = 0) {
super(low, high)
}
/**
* Convert from <code>Number</code>.
*/
public static function fromNumber(n: Number):Int64 {
return new Int64(n, Math.floor(n / 4294967296.0))
}
/**
* Convert to <code>Number</code>.
*/
public final function toNumber():Number {
return high * 4294967296.0 + low
}
public final function toString(radix:uint = 10):String {
if (radix < 2 || radix > 36) {
throw new ArgumentError
}
switch (high) {
case 0:
{
return low.toString(radix)
}
case -1:
{
if ((low & 0x80000000) == 0)
{
return (int(low | 0x80000000) - 2147483648.0).toString(radix)
}
else
{
return int(low).toString(radix)
}
}
default:
{
break;
}
}
if (low == 0 && high == 0) {
return "0"
}
const digitChars:Array = [];
const copyOfThis:UInt64 = new UInt64(low, high);
if (high < 0) {
copyOfThis.bitwiseNot()
copyOfThis.add(1)
}
do {
const digit:uint = copyOfThis.div(radix);
if (digit < 10) {
digitChars.push(digit + CHAR_CODE_0);
} else {
digitChars.push(digit - 10 + CHAR_CODE_A);
}
} while (copyOfThis.high != 0)
if (high < 0) {
return '-' + copyOfThis.low.toString(radix) +
String.fromCharCode.apply(
String, digitChars.reverse())
} else {
return copyOfThis.low.toString(radix) +
String.fromCharCode.apply(
String, digitChars.reverse())
}
}
public static function parseInt64(str:String, radix:uint = 0):Int64 {
const negative:Boolean = str.search(/^\-/) == 0
var i:uint = negative ? 1 : 0
if (radix == 0) {
if (str.search(/^\-?0x/) == 0) {
radix = 16
i += 2
} else {
radix = 10
}
}
if (radix < 2 || radix > 36) {
throw new ArgumentError
}
str = str.toLowerCase()
const result:Int64 = new Int64
for (; i < str.length; i++) {
var digit:uint = str.charCodeAt(i)
if (digit >= CHAR_CODE_0 && digit <= CHAR_CODE_9) {
digit -= CHAR_CODE_0
} else if (digit >= CHAR_CODE_A && digit <= CHAR_CODE_Z) {
digit -= CHAR_CODE_A
digit += 10
} else {
throw new ArgumentError
}
if (digit >= radix) {
throw new ArgumentError
}
result.mul(radix)
result.add(digit)
}
if (negative) {
result.bitwiseNot()
result.add(1)
}
return result
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/Int64.as
|
ActionScript
|
bsd
| 2,950
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
public final class WireType {
public static const VARINT:uint = 0;
public static const FIXED_64_BIT:uint = 1;
public static const LENGTH_DELIMITED:uint = 2;
public static const FIXED_32_BIT:uint = 5;
}
}
|
118194141-test
|
as3/com/netease/protobuf/WireType.as
|
ActionScript
|
bsd
| 537
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import com.netease.protobuf.fieldDescriptors.*;
import flash.errors.IllegalOperationError;
import flash.errors.IOError;
import flash.utils.describeType
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
import flash.utils.IDataInput
import flash.utils.IDataOutput
import flash.utils.ByteArray
public final class TextFormat {
private static function printHex(output:IDataOutput, value:uint):void {
const hexString:String = value.toString(16)
output.writeUTFBytes("00000000".substring(0, 8 - hexString.length))
output.writeUTFBytes(hexString)
}
private static const allEnumValues:Dictionary = new Dictionary
private static function printEnum(output:IDataOutput,
value:int, enumType:Class):void {
var enumValues:Array
if (enumType in allEnumValues) {
enumValues = allEnumValues[enumType]
} else {
const enumTypeDescription:XML = describeType(enumType)
// Not enumTypeDescription.*.@name,
// because haXe will replace all constants to variables, WTF!
const xmlNames:XMLList = enumTypeDescription.*.@name
enumValues = []
for each(var name:String in xmlNames) {
enumValues[enumType[name]] = name
}
allEnumValues[enumType] = enumValues
}
if (value in enumValues) {
output.writeUTFBytes(enumValues[value])
} else {
throw new IOError(value + " is invalid for " +
enumTypeDescription.@name)
}
}
private static function printBytes(output:IDataOutput,
value:ByteArray):void {
output.writeUTFBytes("\"");
value.position = 0
while (value.bytesAvailable > 0) {
const byte:int = value.readByte()
switch (byte) {
case 7: output.writeUTFBytes("\\a" ); break;
case 8: output.writeUTFBytes("\\b" ); break;
case 12: output.writeUTFBytes("\\f" ); break;
case 10: output.writeUTFBytes("\\n" ); break;
case 13: output.writeUTFBytes("\\r" ); break;
case 9: output.writeUTFBytes("\\t" ); break;
case 11: output.writeUTFBytes("\\v" ); break;
case 92: output.writeUTFBytes("\\\\"); break;
case 39: output.writeUTFBytes("\\\'"); break;
case 34 : output.writeUTFBytes("\\\""); break;
default:
if (byte >= 0x20) {
output.writeByte(byte);
} else {
output.writeUTFBytes('\\');
output.writeByte('0'.charCodeAt() + ((byte >>> 6) & 3));
output.writeByte('0'.charCodeAt() + ((byte >>> 3) & 7));
output.writeByte('0'.charCodeAt() + (byte & 7));
}
break;
}
}
output.writeUTFBytes("\"");
}
private static function printString(output:IDataOutput,
value:String):void {
const buffer:ByteArray = new ByteArray
buffer.writeUTFBytes(value)
printBytes(output, buffer)
}
private static function printUnknownField(output:IDataOutput, tag:uint,
value:Object, printSetting:PrintSetting, currentIndent:String):void {
const unknownArray:Array = value as Array
if (unknownArray) {
if (unknownArray.length > 0) {
printSingleUnknownField(output, tag, unknownArray[k],
printSetting, currentIndent)
for (var k:int = 1; k < unknownArray.length; k++) {
output.writeByte(printSetting.newLine)
printSingleUnknownField(output, tag, unknownArray[k],
printSetting, currentIndent)
}
}
} else {
printSingleUnknownField(
output, tag, value, printSetting,
currentIndent)
}
}
private static function printSingleUnknownField(output:IDataOutput,
tag:uint, value:Object, printSetting:PrintSetting,
currentIndent:String):void {
output.writeUTFBytes(currentIndent)
output.writeUTFBytes(String(tag >>> 3))
output.writeUTFBytes(printSetting.simpleFieldSeperator)
switch (tag & 7) {
case WireType.VARINT:
output.writeUTFBytes(UInt64(value).toString())
break
case WireType.FIXED_32_BIT:
output.writeUTFBytes("0x")
printHex(output, uint(value))
break
case WireType.FIXED_64_BIT:
const u64:UInt64 = UInt64(value)
output.writeUTFBytes("0x")
printHex(output, u64.high)
printHex(output, u64.low)
break
case WireType.LENGTH_DELIMITED:
printBytes(output, ByteArray(value))
break
}
}
private static const allMessageFields:Dictionary = new Dictionary
private static function printMessageFields(output:IDataOutput,
message:Message,
printSetting:PrintSetting,
currentIndent:String = ""):void {
var isFirst:Boolean = true
const type:Class = Object(message).constructor
var messageFields:XMLList
if (type in allMessageFields) {
// Fetch in cache
messageFields = allMessageFields[type]
} else {
const description:XML = describeType(type)
// Not description.constant,
// because haXe will replace constant to variable, WTF!
messageFields = description.*.
(
0 == String(@type).search(
/^com.netease.protobuf.fieldDescriptors::(Repeated)?FieldDescriptor\$/) &&
// Not extension
BaseFieldDescriptor(type[@name]).name.search(/\//) == -1
).@name
allMessageFields[type] = messageFields
}
for each (var fieldDescriptorName:String in messageFields) {
const fieldDescriptor:BaseFieldDescriptor =
type[fieldDescriptorName]
const shortName:String = fieldDescriptor.fullName.substring(
fieldDescriptor.fullName.lastIndexOf('.') + 1)
if (fieldDescriptor.type == Array) {
const fieldValues:Array = message[fieldDescriptor.name]
if (fieldValues) {
for (var i:int = 0; i < fieldValues.length; i++) {
if (isFirst) {
isFirst = false
} else {
output.writeByte(printSetting.newLine)
}
output.writeUTFBytes(currentIndent)
output.writeUTFBytes(shortName)
printValue(output, fieldDescriptor, fieldValues[i],
printSetting, currentIndent)
}
}
} else {
const m:Array = fieldDescriptor.name.match(/^(__)?(.)(.*)$/)
m[0] = ""
m[1] = "has"
m[2] = m[2].toUpperCase()
const hasField:String = m.join("")
try {
// optional and does not have that field.
if (false === message[hasField]) {
continue
}
} catch (e:ReferenceError) {
// required
}
if (isFirst) {
isFirst = false
} else {
output.writeByte(printSetting.newLine)
}
output.writeUTFBytes(currentIndent)
output.writeUTFBytes(shortName)
printValue(output, fieldDescriptor,
message[fieldDescriptor.name], printSetting,
currentIndent)
}
}
for (var key:String in message) {
var extension:BaseFieldDescriptor
try {
extension = BaseFieldDescriptor.getExtensionByName(key)
} catch (e:ReferenceError) {
if (key.search(/^[0-9]+$/) == 0) {
// unknown field
if (isFirst) {
isFirst = false
} else {
output.writeByte(printSetting.newLine)
}
printUnknownField(output, uint(key), message[key],
printSetting, currentIndent)
} else {
throw new IOError("Bad unknown field " + key)
}
continue
}
if (extension.type == Array) {
const extensionFieldValues:Array = message[key]
for (var j:int = 0; j < extensionFieldValues.length; j++) {
if (isFirst) {
isFirst = false
} else {
output.writeByte(printSetting.newLine)
}
output.writeUTFBytes(currentIndent)
output.writeUTFBytes("[")
output.writeUTFBytes(extension.fullName)
output.writeUTFBytes("]")
printValue(output, extension,
extensionFieldValues[j], printSetting,
currentIndent)
}
} else {
if (isFirst) {
isFirst = false
} else {
output.writeByte(printSetting.newLine)
}
output.writeUTFBytes(currentIndent)
output.writeUTFBytes("[")
output.writeUTFBytes(extension.fullName)
output.writeUTFBytes("]")
printValue(output, extension, message[key], printSetting,
currentIndent)
}
}
}
private static function printValue(output:IDataOutput,
fieldDescriptor:BaseFieldDescriptor,
value:Object,
printSetting:PrintSetting,
currentIndent:String = ""):void {
const message:Message = value as Message
if (message) {
if (printSetting == SINGLELINE_MODE) {
output.writeUTFBytes("{")
} else {
output.writeUTFBytes(" {\n")
}
printMessageFields(output, message, printSetting,
printSetting.indentChars + currentIndent)
if (printSetting == SINGLELINE_MODE) {
output.writeUTFBytes("}")
} else {
output.writeByte(printSetting.newLine)
output.writeUTFBytes(currentIndent)
output.writeUTFBytes("}")
}
} else {
output.writeUTFBytes(printSetting.simpleFieldSeperator)
const stringValue:String = value as String
if (stringValue !== null) {
printString(output, stringValue)
} else {
const enumFieldDescriptor:FieldDescriptor$TYPE_ENUM =
fieldDescriptor as FieldDescriptor$TYPE_ENUM
if (enumFieldDescriptor) {
printEnum(output, int(value),
enumFieldDescriptor.enumType)
} else {
const enumRepeatedFieldDescriptor:
RepeatedFieldDescriptor$TYPE_ENUM =
fieldDescriptor as
RepeatedFieldDescriptor$TYPE_ENUM
if (enumRepeatedFieldDescriptor) {
printEnum(output, int(value),
enumRepeatedFieldDescriptor.enumType)
} else if (
fieldDescriptor is FieldDescriptor$TYPE_BYTES ||
fieldDescriptor is
RepeatedFieldDescriptor$TYPE_BYTES) {
printBytes(output, ByteArray(value))
} else {
output.writeUTFBytes(value.toString())
}
}
}
}
}
/**
* Outputs a textual representation of the Protocol Message supplied into
* the parameter <code>output</code>.
*/
public static function printToUTFBytes(
output:IDataOutput,
message:Message,
singleLineMode:Boolean = true,
currentIndent:String = ""):void {
printMessageFields(
output,
message,
singleLineMode ? SINGLELINE_MODE : MULTILINE_MODE,
currentIndent)
}
/**
* Like <code>printToUTFBytes()</code>, but writes directly to a String and
* returns it.
*/
public static function printToString(
message:Message,
singleLineMode:Boolean = true,
currentIndent:String = ""):String {
const ba:ByteArray = new ByteArray
printToUTFBytes(ba, message, singleLineMode, currentIndent)
ba.position = 0
return ba.readUTFBytes(ba.length)
}
private static function skipWhitespace(source:ISource):void {
for (;; ) {
const b:int = source.read()
switch (b) {
case 0x20:/* space */
case 0x09:/* \t */
case 0x0a:/* \n */
case 0x0d:/* \r */
continue
case 0x23:/* # */
for (;;) {
switch (source.read()) {
case 0x0a:/* \n */
case 0x0d:/* \r */
break
}
}
break
default:
source.unread(b)
return
}
}
}
private static function toHexDigit(b:int):int {
if (b >= 0x30 && b <= 0x39) {
return b - 0x30
} else if (b >= 0x61 && b <= 0x66) {
return b - 0x57
} else if (b >= 0x41 && b <= 0x46) {
return b - 0x37
} else {
throw new IOError("Expect hex, got " + String.fromCharCode(b))
}
}
private static function toOctalDigit(b:int):int {
if (b >= 0x30 && b <= 0x37) {
return b - 0x30
} else {
throw new IOError("Expect digit, got " + String.fromCharCode(b))
}
}
private static function tryConsumeBytes(source:ISource):ByteArray {
skipWhitespace(source)
const start:int = source.read()
switch (start) {
case 0x22 /* " */:
case 0x27 /* ' */:
const result:ByteArray = new ByteArray
for (;;) {
const b:int = source.read()
switch (b) {
case start:
return result
case 0x5c: /* \ */
const b0:int = source.read()
switch (b0) {
case 0x61 /* \a */: result.writeByte(7); continue;
case 0x62 /* \b */: result.writeByte(8); continue;
case 0x66 /* \f */: result.writeByte(12); continue;
case 0x6e /* \n */: result.writeByte(10); continue;
case 0x72 /* \r */: result.writeByte(13); continue;
case 0x74 /* \t */: result.writeByte(9); continue;
case 0x76 /* \v */: result.writeByte(11); continue;
case 0x78 /* \xXX */:
const x0:int = source.read()
const x1:int = source.read()
result.writeByte(
toHexDigit(x0) * 0x10 +
toHexDigit(x1))
continue
default:
if (b0 >= 0x30 && b0 <= 0x39) {
const b1:int = source.read()
const b2:int = source.read()
result.writeByte(
toOctalDigit(b0) * 64 +
toOctalDigit(b1) * 8 +
toOctalDigit(b2))
} else {
result.writeByte(b0)
}
continue
}
default:
result.writeByte(b)
break
}
}
break
default:
source.unread(start)
break
}
return null
}
private static function tryConsume(source:ISource,
expected:int):Boolean {
skipWhitespace(source)
const b:int = source.read()
if (b == expected) {
return true
} else {
source.unread(b)
return false
}
}
private static function consume(source:ISource, expected:int):void {
skipWhitespace(source)
const b:int = source.read()
if (b != expected) {
throw new IOError("Expect " + String.fromCharCode(expected) +
", got " + String.fromCharCode(b))
}
}
private static function consumeIdentifier(source:ISource):String {
skipWhitespace(source)
const nameBuffer:ByteArray = new ByteArray
for (;; ) {
const b:int = source.read()
if (b >= 0x30 && b <= 0x39 || // 0-9
b >= 0x41 && b <= 0x5a || // A-Z
b >= 0x61 && b <= 0x7a || // a-z
b == 0x2e || b == 0x5f || b == 0x2d || b < 0) {
nameBuffer.writeByte(b)
} else {
if (nameBuffer.length == 0) {
throw new IOError("Expect Identifier, got " +
String.fromCharCode(b))
}
source.unread(b)
break
}
}
nameBuffer.position = 0
return nameBuffer.readUTFBytes(nameBuffer.length)
}
private static function appendUnknown(message:Message, tag:uint,
value:*):void {
const oldValue:* = message[tag]
if (oldValue === undefined) {
message[tag] = value
} else {
const oldArray:Array = oldValue as Array
if (oldArray) {
oldArray.push(value)
} else {
message[tag] = [oldValue, value]
}
}
}
private static function consumeUnknown(source:ISource,
message:Message, number:uint):void {
const bytes:ByteArray = tryConsumeBytes(source)
if (bytes) {
appendUnknown(message,
(number << 3) | WireType.LENGTH_DELIMITED,
bytes)
return
}
const identifier:String = consumeIdentifier(source)
const m:Array = identifier.match(
/^0[xX]([0-9a-fA-F]{16}|[0-9a-fA-F]{8})$/)
if (!m) {
appendUnknown(message,
(number << 3) | WireType.VARINT,
UInt64.parseUInt64(identifier))
return
}
const hex:String = m[1]
if (hex.length == 8) {
appendUnknown(message,
(number << 3) | WireType.FIXED_32_BIT,
uint(parseInt(hex, 16)))
} else {
appendUnknown(message,
(number << 3) | WireType.FIXED_64_BIT,
UInt64.parseUInt64(hex, 16))
}
}
private static function consumeEnumFieldValue(source:ISource,
enumType:Class):int {
consume(source, 0x3a/* : */)
const enumName:String = consumeIdentifier(source)
const result:* = enumType[enumName]
if (result === undefined) {
throw new IOError("Invalid enum name " + enumName)
} else {
return result
}
}
private static function parseUnknown(message:Message):void {
const buffer:WritingBuffer = new WritingBuffer
for (var fieldName:String in message) {
const tag:uint = uint(fieldName)
if (tag == 0) {
continue
}
WriteUtils.writeUnknownPair(buffer, tag, message[fieldName])
delete message[fieldName]
}
const normalBuffer:ByteArray = new ByteArray
buffer.toNormal(normalBuffer)
normalBuffer.position = 0
message.mergeFrom(normalBuffer)
}
private static function consumeFieldValue(source:ISource,
type:Class):* {
switch (type) {
case ByteArray:
consume(source, 0x3a/* : */)
const bytes:ByteArray = tryConsumeBytes(source)
if (bytes) {
bytes.position = 0
return bytes
} else {
throw new IOError("Expect quoted bytes")
}
case String:
consume(source, 0x3a/* : */)
const binaryString:ByteArray = tryConsumeBytes(source)
if (binaryString) {
binaryString.position = 0
return binaryString.readUTFBytes(binaryString.length)
} else {
throw new IOError("Expect quoted string")
}
case Boolean:
consume(source, 0x3a/* : */)
const booleanString:String = consumeIdentifier(source)
switch (booleanString) {
case "true":
return true
case "false":
return false
default:
throw new IOError("Expect boolean, got " +
booleanString)
}
break
case Int64:
consume(source, 0x3a/* : */)
return Int64.parseInt64(consumeIdentifier(source))
case UInt64:
consume(source, 0x3a/* : */)
return UInt64.parseUInt64(consumeIdentifier(source))
case uint:
consume(source, 0x3a/* : */)
return uint(parseInt(consumeIdentifier(source)))
case int:
consume(source, 0x3a/* : */)
return int(parseInt(consumeIdentifier(source)))
case Number:
consume(source, 0x3a/* : */)
return parseFloat(consumeIdentifier(source))
default:
tryConsume(source, 0x3a/* : */)
consume(source, 0x7b/* { */)
const message:Message = new type
for (;; ) {
if (tryConsume(source, 0x7d/* } */)) {
break
}
consumeField(source, message)
}
parseUnknown(message)
return message
}
}
private static function consumeField(source:ISource,
message:Message):void {
const isExtension:Boolean = tryConsume(source, 0x5b /* [ */)
const name:String = consumeIdentifier(source)
if (isExtension) {
consume(source, 0x5d /* ] */)
}
var fieldDescriptor:BaseFieldDescriptor
if (isExtension) {
const lastDotPosition:int = name.lastIndexOf('.')
const scope:String = name.substring(0, lastDotPosition)
const localName:String = name.substring(lastDotPosition + 1)
try {
fieldDescriptor = getDefinitionByName(scope)[
localName.toUpperCase()]
} catch (e:ReferenceError) {
try {
fieldDescriptor = BaseFieldDescriptor(
getDefinitionByName(scope + '.' +
localName.toUpperCase()))
} catch (e:ReferenceError) {
throw new IOError("Unknown extension: " + name)
}
}
} else {
if (name.search(/[0-9]+/) == 0) {
consume(source, 0x3a/* : */)
consumeUnknown(source, message, uint(name))
return
} else {
fieldDescriptor = Object(message).constructor[
name.toUpperCase()]
if (!fieldDescriptor) {
throw new IOError("Unknown field: " + name);
}
}
}
const repeatedFieldDescriptor:RepeatedFieldDescriptor =
fieldDescriptor as RepeatedFieldDescriptor
if (repeatedFieldDescriptor) {
const destination:Array =
message[fieldDescriptor.name] ||
(message[fieldDescriptor.name] = [])
const enumRepeatedFieldDescriptor:
RepeatedFieldDescriptor$TYPE_ENUM =
repeatedFieldDescriptor as
RepeatedFieldDescriptor$TYPE_ENUM
destination.push(enumRepeatedFieldDescriptor ?
consumeEnumFieldValue(source,
enumRepeatedFieldDescriptor.enumType) :
consumeFieldValue(source,
repeatedFieldDescriptor.elementType))
} else {
const enumFieldDescriptor:FieldDescriptor$TYPE_ENUM =
fieldDescriptor as FieldDescriptor$TYPE_ENUM
message[fieldDescriptor.name] = enumFieldDescriptor ?
consumeEnumFieldValue(source,
enumFieldDescriptor.enumType) :
consumeFieldValue(source,
fieldDescriptor.type)
}
}
private static function mergeFromSource(source:ISource,
message:Message):void {
for (;; ) {
if (tryConsume(source, 0/* EOF */)) {
break
}
consumeField(source, message)
}
parseUnknown(message)
}
/**
* Parse a text-format message from <code>input</code> and merge the
* contents into <code>message</code>.
*/
public static function mergeFromUTFBytes(input:IDataInput,
message:Message):void {
mergeFromSource(new WrappedSource(input), message)
}
/**
* Parse a text-format message from <code>text</code> and merge the
* contents into <code>message</code>.
*/
public static function mergeFromString(text:String, message:Message):void {
const source:BufferedSource = new BufferedSource
source.writeUTFBytes(text)
source.position = 0
mergeFromSource(source, message)
}
}
}
import flash.errors.IOError;
import flash.utils.IDataInput;
import flash.utils.ByteArray;
import flash.errors.EOFError
interface ISource {
function read():int
function unread(b:int):void
}
class BufferedSource extends ByteArray implements ISource {
public function unread(value:int):void {
if (value == 0 && bytesAvailable == 0) {
return
}
position--
}
public function read():int {
if (bytesAvailable > 0) {
return readByte()
} else {
return 0
}
}
}
class WrappedSource implements ISource {
private var input:IDataInput
private var temp:int
public function WrappedSource(input:IDataInput) {
this.input = input
}
public function unread(value:int):void {
if (temp) {
throw new IOError("Cannot unread twice!")
}
temp = value
}
public function read():int {
if (temp) {
const result:int = temp
temp = 0
return result
} else {
try {
return input.readByte()
} catch (e: EOFError) {
}
return 0
}
}
}
class PrintSetting {
public var newLine:uint
public var indentChars:String
public var simpleFieldSeperator:String
}
const SINGLELINE_MODE:PrintSetting = new PrintSetting
SINGLELINE_MODE.newLine = ' '.charCodeAt()
SINGLELINE_MODE.indentChars = ""
SINGLELINE_MODE.simpleFieldSeperator = ":"
const MULTILINE_MODE:PrintSetting = new PrintSetting
MULTILINE_MODE.newLine = '\n'.charCodeAt()
MULTILINE_MODE.indentChars = " "
MULTILINE_MODE.simpleFieldSeperator = ": "
|
118194141-test
|
as3/com/netease/protobuf/TextFormat.as
|
ActionScript
|
bsd
| 22,609
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.net.*;
import flash.utils.*;
import flash.events.*;
/**
* A simple sample of RPC implementation.
*/
public final class SimpleWebRPC {
private var urlPrefix:String
public function SimpleWebRPC(urlPrefix:String) {
this.urlPrefix = urlPrefix
}
private static const REF:Dictionary = new Dictionary
public function send(qualifiedMethodName:String,
requestMessage:Message,
rpcResult:Function,
responseClass:Class):void {
const loader:URLLoader = new URLLoader
REF[loader] = true;
loader.dataFormat = URLLoaderDataFormat.BINARY
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
delete REF[loader]
const responseMessage:Message = new responseClass
responseMessage.mergeFrom(loader.data)
rpcResult(responseMessage)
})
function errorEventHandler(event:Event):void {
delete REF[loader]
rpcResult(event)
}
loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler)
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR, errorEventHandler)
const request:URLRequest = new URLRequest(
urlPrefix + qualifiedMethodName.replace(/\./g, "/").
replace(/^((com|org|net)\/\w+\/\w+\/)?(.*)$/, "$3"))
const requestContent:ByteArray = new ByteArray
requestMessage.writeTo(requestContent)
if (requestContent.length != 0)
{
request.data = requestContent
}
request.contentType = "application/x-protobuf"
request.method = URLRequestMethod.POST
loader.load(request)
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/SimpleWebRPC.as
|
ActionScript
|
bsd
| 1,855
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
public final class UInt64 extends Binary64 {
public final function set high(value:uint):void {
internalHigh = value
}
public final function get high():uint {
return internalHigh
}
public function UInt64(low:uint = 0, high:uint = 0) {
super(low, high)
}
/**
* Convert from <code>Number</code>.
*/
public static function fromNumber(n: Number):UInt64 {
return new UInt64(n, Math.floor(n / 4294967296.0))
}
/**
* Convert to <code>Number</code>.
*/
public final function toNumber():Number {
return (high * 4294967296) + low
}
public final function toString(radix:uint = 10):String {
if (radix < 2 || radix > 36) {
throw new ArgumentError
}
if (high == 0) {
return low.toString(radix)
}
const digitChars:Array = [];
const copyOfThis:UInt64 = new UInt64(low, high);
do {
const digit:uint = copyOfThis.div(radix);
if (digit < 10) {
digitChars.push(digit + CHAR_CODE_0);
} else {
digitChars.push(digit - 10 + CHAR_CODE_A);
}
} while (copyOfThis.high != 0)
return copyOfThis.low.toString(radix) +
String.fromCharCode.apply(
String, digitChars.reverse())
}
public static function parseUInt64(str:String, radix:uint = 0):UInt64 {
var i:uint = 0
if (radix == 0) {
if (str.search(/^0x/) == 0) {
radix = 16
i = 2
} else {
radix = 10
}
}
if (radix < 2 || radix > 36) {
throw new ArgumentError
}
str = str.toLowerCase()
const result:UInt64 = new UInt64
for (; i < str.length; i++) {
var digit:uint = str.charCodeAt(i)
if (digit >= CHAR_CODE_0 && digit <= CHAR_CODE_9) {
digit -= CHAR_CODE_0
} else if (digit >= CHAR_CODE_A && digit <= CHAR_CODE_Z) {
digit -= CHAR_CODE_A
digit += 10
} else {
throw new ArgumentError
}
if (digit >= radix) {
throw new ArgumentError
}
result.mul(radix)
result.add(digit)
}
return result
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/UInt64.as
|
ActionScript
|
bsd
| 2,276
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
public class Binary64 {
/**
* @private
*/
internal static const CHAR_CODE_0:uint = '0'.charCodeAt();
/**
* @private
*/
internal static const CHAR_CODE_9:uint = '9'.charCodeAt();
/**
* @private
*/
internal static const CHAR_CODE_A:uint = 'a'.charCodeAt();
/**
* @private
*/
internal static const CHAR_CODE_Z:uint = 'z'.charCodeAt();
public var low:uint;
/**
* @private
*/
internal var internalHigh:uint;
public function Binary64(low:uint = 0, high:uint = 0) {
this.low = low
this.internalHigh = high
}
/**
* Division by n.
* @return The remainder after division.
* @private
*/
internal final function div(n:uint):uint {
const modHigh:uint = internalHigh % n
const mod:uint = (low % n + modHigh * 6) % n
internalHigh /= n
const newLow:Number = (modHigh * 4294967296.0 + low) / n
internalHigh += uint(newLow / 4294967296.0)
low = newLow
return mod
}
/**
* @private
*/
internal final function mul(n:uint):void {
const newLow:Number = Number(low) * n
internalHigh *= n
internalHigh += uint(newLow / 4294967296.0)
low *= n
}
/**
* @private
*/
internal final function add(n:uint):void {
const newLow:Number = Number(low) + n
internalHigh += uint(newLow / 4294967296.0)
low = newLow
}
/**
* @private
*/
internal final function bitwiseNot():void {
low = ~low
internalHigh = ~internalHigh
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/Binary64.as
|
AngelScript
|
bsd
| 1,765
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.fieldDescriptors {
import com.netease.protobuf.*
import flash.utils.*
/**
* @private
*/
public final class FieldDescriptor$TYPE_FIXED64 extends
FieldDescriptor {
public function FieldDescriptor$TYPE_FIXED64(
fullName:String, name:String, tag:uint) {
this.fullName = fullName
this._name = name
this.tag = tag
}
override public function get type():Class {
return Int64
}
override public function readSingleField(input:IDataInput):* {
return ReadUtils.read$TYPE_FIXED64(input)
}
override public function writeSingleField(output:WritingBuffer,
value:*):void {
WriteUtils.write$TYPE_FIXED64(output, value)
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/fieldDescriptors/FieldDescriptor$TYPE_FIXED64.as
|
ActionScript
|
bsd
| 973
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.fieldDescriptors {
import com.netease.protobuf.*
import flash.utils.*
/**
* @private
*/
public final class RepeatedFieldDescriptor$TYPE_FIXED64 extends
RepeatedFieldDescriptor {
public function RepeatedFieldDescriptor$TYPE_FIXED64(
fullName:String, name:String, tag:uint) {
this.fullName = fullName
this._name = name
this.tag = tag
}
override public function get nonPackedWireType():int {
return WireType.FIXED_64_BIT
}
override public function get type():Class {
return Array
}
override public function get elementType():Class {
return Int64
}
override public function readSingleField(input:IDataInput):* {
return ReadUtils.read$TYPE_FIXED64(input)
}
override public function writeSingleField(output:WritingBuffer,
value:*):void {
WriteUtils.write$TYPE_FIXED64(output, value)
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/fieldDescriptors/RepeatedFieldDescriptor$TYPE_FIXED64.as
|
ActionScript
|
bsd
| 1,163
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.fieldDescriptors {
import com.netease.protobuf.*
import flash.utils.*
/**
* @private
*/
public final class FieldDescriptor$TYPE_SFIXED64 extends
FieldDescriptor {
public function FieldDescriptor$TYPE_SFIXED64(
fullName:String, name:String, tag:uint) {
this.fullName = fullName
this._name = name
this.tag = tag
}
override public function get type():Class {
return Int64
}
override public function readSingleField(input:IDataInput):* {
return ReadUtils.read$TYPE_SFIXED64(input)
}
override public function writeSingleField(output:WritingBuffer,
value:*):void {
WriteUtils.write$TYPE_SFIXED64(output, value)
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/fieldDescriptors/FieldDescriptor$TYPE_SFIXED64.as
|
ActionScript
|
bsd
| 977
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.fieldDescriptors {
import com.netease.protobuf.*
import flash.utils.*
/**
* @private
*/
public final class FieldDescriptor$TYPE_STRING extends
FieldDescriptor {
public function FieldDescriptor$TYPE_STRING(
fullName:String, name:String, tag:uint) {
this.fullName = fullName
this._name = name
this.tag = tag
}
override public function get type():Class {
return String
}
override public function readSingleField(input:IDataInput):* {
return ReadUtils.read$TYPE_STRING(input)
}
override public function writeSingleField(output:WritingBuffer,
value:*):void {
WriteUtils.write$TYPE_STRING(output, value)
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/fieldDescriptors/FieldDescriptor$TYPE_STRING.as
|
ActionScript
|
bsd
| 970
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf.fieldDescriptors {
import com.netease.protobuf.*
import flash.utils.*
/**
* @private
*/
public final class RepeatedFieldDescriptor$TYPE_FLOAT extends
RepeatedFieldDescriptor {
public function RepeatedFieldDescriptor$TYPE_FLOAT(
fullName:String, name:String, tag:uint) {
this.fullName = fullName
this._name = name
this.tag = tag
}
override public function get nonPackedWireType():int {
return WireType.FIXED_32_BIT
}
override public function get type():Class {
return Array
}
override public function get elementType():Class {
return Number
}
override public function readSingleField(input:IDataInput):* {
return ReadUtils.read$TYPE_FLOAT(input)
}
override public function writeSingleField(output:WritingBuffer,
value:*):void {
WriteUtils.write$TYPE_FLOAT(output, value)
}
}
}
|
118194141-test
|
as3/com/netease/protobuf/fieldDescriptors/RepeatedFieldDescriptor$TYPE_FLOAT.as
|
ActionScript
|
bsd
| 1,156
|