file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
client/router.js | JavaScript | 'use strict';
var Router = require('ampersand-router');
var App = require('ampersand-app');
var Pages = require('./pages');
var UserActivities = require('./models/activities');
var WorkoutModel = require('./models/workout');
var WendlerModel = require('./models/wendler531');
var ActivityModel = require('./models/activity');
var ActivityHistories = require('./models/activity-histories');
var AdminUsers = require('./models/admin-users');
module.exports = Router.extend({
routes: {
//Unauthenticated
'': 'home',
'about(/)': 'about',
'news(/)': 'news',
'old-news(/)': 'oldNews',
'login(/)': 'login',
'signup(/)': 'signup',
'privacy(/)': 'privacy',
'recover(/)': 'recover',
'public/workouts/:id(/)': 'publicWorkout',
'tools(/)': 'tools',
'tools/531(/)': 'wendler531',
//Authenticated
'workouts(/)': 'workouts',
'workouts/new(/)': 'editWorkout',
'workouts/:date(/)': 'showWorkout',
'workouts/:date/edit(/)': 'editWorkout',
'activities(/)': 'activities',
'activities/:id/history(/)': 'activityHistory',
'me(/)': 'me',
'me/invites(/)': 'invites',
'validate(/)': 'validate',
'logout(/)': 'logout',
//Admin
'admin(/)': 'admin',
//Catchall
'*catchall': 'notfound'
},
//Unauthenticated routes
notfound: function () {
this.trigger('page', new Pages['not-found']());
},
privacy: function () {
this.trigger('page', new Pages.privacy());
},
home: function () {
this.trigger('page', new Pages.home({ assetsUrl: App.assetsUrl }));
},
about: function () {
this.trigger('page', new Pages.about({ assetsUrl: App.assetsUrl }));
},
news: function () {
this.trigger('page', new Pages.news());
},
oldNews: function () {
this.trigger('page', new Pages.oldNews());
},
login: function () {
this.trigger('page', new Pages.login());
},
logout: function () {
App.setAccessToken(undefined);
this.redirectTo('/');
},
signup: function () {
this.trigger('page', new Pages.signup());
},
recover: function () {
if (App.me.loggedIn) {
return this.navigate('/me');
}
this.trigger('page', new Pages.recover());
},
publicWorkout: function (id) {
this.trigger('page', new Pages.publicWorkout({ model: new WorkoutModel({ id: id }) }));
},
tools: function () {
this.trigger('page', new Pages.tools());
},
wendler531: function () {
this.trigger('page', new Pages.wendler531({ model: new WendlerModel() }));
},
//Authenticated routes
validate: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.validate({ model: App.me }));
},
me: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.me({ model: App.me }));
},
invites: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.invites({ model: App.me }));
},
newWorkout: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.editWorkout({ model: new WorkoutModel() }));
},
editWorkout: function (date) {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
if (App.workoutSummaries.fetched) {
return this.trigger('page', new Pages.editWorkout({ date: date, model: new WorkoutModel() }));
}
this.listenToOnce(App.workoutSummaries, 'reset', function () {
return this.trigger('page', new Pages.editWorkout({ date: date, model: new WorkoutModel() }));
});
},
showWorkout: function (date) {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
if (App.workoutSummaries.fetched) {
return this.trigger('page', new Pages.showWorkout({ date: date, model: new WorkoutModel() }));
}
this.listenToOnce(App.workoutSummaries, 'reset', function () {
return this.trigger('page', new Pages.showWorkout({ date: date, model: new WorkoutModel() }));
});
},
workouts: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.workouts());
},
activities: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.activities({ collection: new UserActivities() }));
},
activityHistory: function (id) {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
this.trigger('page', new Pages.activityHistory({ model: new ActivityModel({ id: id }), collection: new ActivityHistories({ id: id }) }));
},
admin: function () {
if (!App.me.loggedIn) {
return this.navigate('/login');
}
if (!App.me.isAdmin) {
return this.trigger('page', new Pages['not-found']());
}
this.trigger('page', new Pages.admin({ collection: new AdminUsers() }));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/activity-history.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var SetView = View.extend({
template: require('../templates/views/activity-history-set.pug'),
bindings: {
'model.formattedShort': {
type: 'text',
hook: 'set'
},
'model.pr': {
type: 'booleanClass',
hook: 'set',
class: 'pr'
}
}
});
module.exports = View.extend({
template: require('../templates/views/activity-history.pug'),
render: function () {
this.renderWithTemplate();
this.renderCollection(this.model.sets, SetView, this.queryByHook('sets'));
},
bindings: {
'model.workout_name': {
type: 'text',
hook: 'workout-name'
},
'model.workout_date': {
type: 'text',
hook: 'workout-date'
},
'model.showUrl': {
type: 'attribute',
name: 'href',
hook: 'workout-name'
},
'model.comment': {
type: 'text',
hook: 'activity-comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'toggle-comment'
}
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/activity.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var SuggestionView = require('./suggestion');
var SetView = View.extend({
template: require('../templates/views/set.pug'),
bindings: {
'model.formattedFull': {
type: 'text',
hook: 'set'
}
}
});
module.exports = View.extend({
template: require('../templates/views/workout-activity.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'activity-name'
},
'model.comment': [{
type: 'text',
hook: 'activity-comment'
}, {
type: 'toggle',
hook: 'activity-comment'
}],
'model.ready': {
type: 'toggle',
no: '[data-hook=new-activity]'
},
'model.hasSuggestions': {
type: 'toggle',
hook: 'has-suggestions'
}
},
events: {
'click [data-hook=new-activity]': 'findAlias'
},
render: function () {
this.renderWithTemplate(this);
this.renderSubview(new SuggestionView({ model: this.model }), this.queryByHook('new-confirm'));
this.renderCollection(this.model.sets, SetView, this.queryByHook('sets'));
this.renderCollection(this.model.suggestions, SuggestionView, this.queryByHook('suggestions'));
this.cacheElements({ aliasModal: '[data-hook=choose-alias]' });
$(this.el).foundation();
return this;
},
findAlias: function () {
$(this.aliasModal).foundation('reveal', 'open');
},
closeModal: function () {
$(this.aliasModal).foundation('reveal', 'close');
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/admin-user.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
template: require('../templates/views/admin-user.pug'),
bindings: {
'model.name': {
type: 'text',
hook: 'name'
},
'model.validated': {
type: 'toggle',
hook: 'validated'
},
'model.workouts': {
type: 'text',
hook: 'workouts'
},
'model.activities': {
type: 'text',
hook: 'activities'
},
'model.invites': {
type: 'text',
hook: 'invites'
}
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/bbcode-activity-long.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var RepView = View.extend({
template: require('../templates/views/bbcode-rep-long.pug'),
bindings: {
'model.formattedFull': {
type: 'text',
hook: 'rep'
},
'model.pr': {
type: 'toggle',
hook: 'pr'
}
}
});
module.exports = View.extend({
template: require('../templates/views/bbcode-activity.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'comment-label'
}
},
render: function () {
this.renderWithTemplate();
this.renderCollection(this.model.sets, RepView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/bbcode-activity-short.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var GroupedCollectionView = require('ampersand-grouped-collection-view');
var RepView = View.extend({
template: require('../templates/views/bbcode-rep-short.pug'),
bindings: {
'model.formattedShort': {
type: 'text',
hook: 'rep'
},
'model.pr': {
type: 'toggle',
hook: 'pr'
},
'model.lastInGroup': {
type: 'toggle',
hook: 'repsep',
invert: true
}
}
});
var SetGroupView = View.extend({
template: require('../templates/views/bbcode-set-group.pug'),
render: function () {
this.renderWithTemplate();
this.cacheElements({
groupEl: '[data-hook=set-group]'
});
}
});
module.exports = View.extend({
template: require('../templates/views/bbcode-activity.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'comment-label'
}
},
render: function () {
if (this.model.sets.length > 0) {
this.model.sets.at(this.model.sets.length - 1).lastInGroup = true;
}
this.renderWithTemplate();
var setView = new GroupedCollectionView({
collection: this.model.sets,
itemView: RepView,
groupView: SetGroupView,
groupsWith: function (model, prevModel) {
return (model.collection.indexOf(model) % 3) !== 0;
},
prepareGroup: function (model, prevGroupModel) {
var lastInGroup = model.collection.indexOf(model) + 2;
if (lastInGroup < model.collection.length) {
model.collection.at(lastInGroup).lastInGroup = true;
}
return model;
}
});
setView.render();
this.renderSubview(setView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/bbcode-credits.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
template: require('../templates/views/bbcode-credits.pug'),
autoRender: true
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/bbcode-full.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var RepView = require('../views/bbcode-rep');
module.exports = View.extend({
template: require('../templates/views/bbcode.pug'),
bindings: {
'model.name': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'commentLabel'
}
},
render: function () {
this.renderWithTemplate();
this.renderCollection(this.model.sets, RepView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/bbcode-rep.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
template: require('../templates/views/bbcode-rep.pug'),
bindings: {
'model.formattedFull': {
type: 'text',
hook: 'rep'
},
'model.nonpr': {
type: 'booleanClass',
name: 'nonpr',
hook: 'pr'
}
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/bbcode.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var GroupedCollectionView = require('ampersand-grouped-collection-view');
var RepItemView = View.extend({
template: require('../templates/views/bbcode-rep-item.pug'),
bindings: {
'model.formattedShort': {
type: 'text',
hook: 'rep'
},
'model.nonpr': {
type: 'booleanClass',
name: 'nonpr',
hook: 'pr'
}
}
});
var RepGroupView = View.extend({
template: require('../templates/views/bbcode-rep-group.pug'),
render: function () {
this.renderWithTemplate();
this.cacheElements({
groupEl: '[data-hook=repGroup]'
});
}
});
module.exports = View.extend({
template: require('../templates/views/bbcode.pug'),
bindings: {
'model.name': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'commentLabel'
}
},
render: function () {
this.renderWithTemplate();
var repView = new GroupedCollectionView({
collection: this.model.sets,
itemView: RepItemView,
groupView: RepGroupView,
groupsWith: function (model) {
if (model.collection.length < 6) {
return true;
}
return (model.collection.indexOf(model) % 3) !== 0;
},
prepareGroup: function (model) {
return model;
}
});
repView.render();
this.renderSubview(repView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/invite.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
template: require('../templates/views/signup-invite.pug'),
session: {
status: 'string'
},
bindings: {
'model.token': {
type: 'attribute',
hook: 'token',
name: 'value'
},
'status': [
{
type: 'text',
hook: 'invite-status'
}, {
type: 'toggle',
hook: 'invite-status'
}
]
},
events: {
'submit form': 'checkInvite'
},
render: function () {
this.renderWithTemplate(this);
if (this.model.token) {
this.checkInvite();
}
return this;
},
checkInvite: function (e) {
if (e) {
e.preventDefault();
}
var self = this;
self.status = 'Checking invite...';
var token = self.query('[name=invite]').value;
self.model.token = token;
self.model.fetch({
success: function () {
self.status = '';
self.parent.stage = 'signup';
},
error: function () {
self.status = '';
$(self.queryByHook('invalid')).foundation('reveal', 'open');
}
});
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/lift531.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
template: require('../templates/views/lift531.pug'),
autoRender: true,
render: function () {
this.listenToAndRun(this.model, 'change:waves', this.reRender);
},
reRender: function () {
this.renderWithTemplate(this.model);
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/markdown-activity-long.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var RepView = View.extend({
template: require('../templates/views/markdown-rep-long.pug'),
bindings: {
'model.formattedFull': {
type: 'text',
hook: 'rep'
},
'model.pr': {
type: 'toggle',
hook: 'pr'
}
}
});
module.exports = View.extend({
template: require('../templates/views/markdown-activity.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'comment-label'
}
},
render: function () {
this.renderWithTemplate();
this.renderCollection(this.model.sets, RepView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/markdown-activity-short.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var GroupedCollectionView = require('ampersand-grouped-collection-view');
var RepView = View.extend({
template: require('../templates/views/markdown-rep-short.pug'),
bindings: {
'model.formattedShort': {
type: 'text',
hook: 'rep'
},
'model.pr': {
type: 'toggle',
hook: 'pr'
},
'model.lastInGroup': {
type: 'toggle',
hook: 'repsep',
invert: true
}
}
});
var SetGroupView = View.extend({
template: require('../templates/views/markdown-set-group.pug'),
render: function () {
this.renderWithTemplate();
this.cacheElements({
groupEl: '[data-hook=set-group]'
});
}
});
module.exports = View.extend({
template: require('../templates/views/markdown-activity.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'comment-label'
}
},
render: function () {
if (this.model.sets.length > 0) {
this.model.sets.at(this.model.sets.length - 1).lastInGroup = true;
}
this.renderWithTemplate();
var setView = new GroupedCollectionView({
collection: this.model.sets,
itemView: RepView,
groupView: SetGroupView,
groupsWith: function (model, prevModel) {
return (model.collection.indexOf(model) % 3) !== 0;
},
prepareGroup: function (model, prevGroupModel) {
var lastInGroup = model.collection.indexOf(model) + 2;
if (lastInGroup < model.collection.length) {
model.collection.at(lastInGroup).lastInGroup = true;
}
return model;
}
});
setView.render();
this.renderSubview(setView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/markdown-credits.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
template: require('../templates/views/markdown-credits.pug'),
autoRender: true
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/markdown-full.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var RepView = require('../views/markdown-rep');
module.exports = View.extend({
template: require('../templates/views/markdown.pug'),
bindings: {
'model.name': {
type: 'text',
hook: 'name'
},
'model.comment': {
type: 'text',
hook: 'comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'commentLabel'
}
},
render: function () {
this.renderWithTemplate();
this.renderCollection(this.model.sets, RepView, this.queryByHook('sets'));
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/recover.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var App = require('ampersand-app');
var Sync = require('ampersand-sync');
module.exports = View.extend({
template: require('../templates/views/recover.pug'),
events: {
'submit form': 'reset'
},
reset: function (e) {
e.preventDefault();
var password = this.query('[name=password]').value;
var passwordConfirm = this.query('[name=passwordConfirm]').value;
var payload = {
token: this.parent.token,
password: password,
passwordConfirm: passwordConfirm
};
var syncOptions = {
url: App.apiUrl + '/user/reset',
json: payload,
success: function (resp) {
App.setAccessToken(resp.token);
App.navigate('/');
App.view.message = 'All set, from now on log in with that password. Go use the lift zone';
},
error: function () {
App.view.message = 'Invalid recovery token.';
}
};
Sync('create', null, syncOptions);
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/request-recover.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var App = require('ampersand-app');
var Sync = require('ampersand-sync');
module.exports = View.extend({
template: require('../templates/views/request-recover.pug'),
events: {
'submit form': 'request'
},
request: function (e) {
e.preventDefault(e);
App.view.message = '';
var email = this.query('[name=email]').value;
var payload = {
email: email
};
var syncOptions = {
headers: App.me.ajaxConfig().headers,
url: App.apiUrl + '/user/recover',
json: payload,
success: function (model, resp) {
App.view.message = 'Email sent, good luck. Check your inbox and click the link. The link expires in three hours.';
},
error: function () {
App.view.message = 'Unknown error trying to validate.';
}
};
Sync('create', null, syncOptions);
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/request-validation.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var App = require('ampersand-app');
var Sync = require('ampersand-sync');
module.exports = View.extend({
template: require('../templates/views/request-validation.pug'),
events: {
'click [data-hook=request]': 'request'
},
bindings: {
'model.email': {
type: 'text',
hook: 'email'
}
},
request: function () {
App.view.message = '';
var syncOptions = {
headers: App.me.ajaxConfig().headers,
url: App.apiUrl + '/user/validate',
success: function (model, resp) {
App.view.message = 'Email sent. Check your inbox and click the link. The link expires in one day.';
},
error: function () {
App.view.message = 'Unknown error trying to validate.';
}
};
Sync('create', null, syncOptions);
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/signup.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var App = require('ampersand-app');
var Sync = require('ampersand-sync');
module.exports = View.extend({
template: require('../templates/views/signup.pug'),
events: {
'submit form': 'signup'
},
signup: function (e) {
e.preventDefault();
var self = this;
var payload = {
invite: self.model.token,
name: self.query('[name=name]').value,
email: self.query('[name=email]').value,
password: self.query('[name=password]').value,
passwordConfirm: self.query('[name=passwordConfirm]').value
};
var syncOptions = {
url: App.apiUrl + '/user/signup',
json: payload,
success: function (response) {
App.setAccessToken(response.token);
App.navigate('/');
},
error: function (err) {
if (err.statusCode === 409) {
$(self.queryByHook('taken')).foundation('reveal', 'open');
}
else {
$(self.queryByHook('error')).foundation('reveal', 'open');
}
}
};
Sync('create', null, syncOptions);
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/suggestion.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
autoRender: true,
template: require('../templates/views/suggestion.pug'),
events: {
'click [data-hook=name]': 'chooseAlias'
},
bindings: {
'model.name': {
type: 'text',
hook: 'name'
}
},
chooseAlias: function (e) {
e.preventDefault();
var self = this;
if (this.model.suggestions) {
this.model.save({
name: this.model.name
}, {
success: function () {
self.parent.closeModal();
}
});
}
else {
this.model.collection.parent.save({
name: this.model.collection.parent.name,
activity_id: this.model.activity_id
}, {
success: function () {
self.parent.closeModal();
}
});
}
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/user-activity.js | JavaScript | 'use strict';
var App = require('ampersand-app');
var View = require('ampersand-view');
var Sync = require('ampersand-sync');
var AliasView = View.extend({
template: require('../templates/views/user-alias.pug'),
bindings: {
'model.name': {
type: 'text',
hook: 'name'
}
},
events: {
'click [data-hook=promote]': 'promote'
},
promote: function () {
var self = this;
var oldActivity = self.model.collection.parent;
var activities = self.model.collection.parent.collection;
var syncOptions = {
headers: {
Authorization: 'Bearer ' + App.accessToken
},
url: self.model.url() + '/promote',
success: function (response) {
activities.remove(oldActivity);
activities.add(response);
},
error: function (err) {
if (err.statusCode === 409) {
$(self.queryByHook('taken')).foundation('reveal', 'open');
}
else {
$(self.queryByHook('error')).foundation('reveal', 'open');
}
}
};
Sync('update', null, syncOptions);
}
});
var ActivityView = View.extend({
template: require('../templates/views/user-activity.pug'),
bindings: {
'model.historyUrl': {
type: 'attribute',
name: 'href',
hook: 'name'
},
'model.name': {
type: 'text',
hook: 'name'
}
},
events: {
'submit form[data-hook=alias-form]': 'addAlias'
},
render: function () {
this.renderWithTemplate(this);
$(this.el).foundation();
this.renderCollection(this.model.aliases, AliasView, this.queryByHook('aliases'));
},
addAlias: function (e) {
e.preventDefault();
App.view.message = '';
var self = this;
var name = self.query('[name=alias]').value;
var alias = new self.model.aliases.model({ name: name, activity_id: this.model.id });
alias.save(null, {
success: function () {
self.model.aliases.add(alias);
self.query('[name=alias]').value = '';
},
error: function (model, newAlias, ctx) {
if (ctx.xhr.status === 409) {
$(self.queryByHook('alias-exists')).foundation('reveal', 'open');
}
else {
App.view.message = 'Unknown error trying to save alias';
}
}
});
}
});
module.exports = ActivityView;
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/validate.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var App = require('ampersand-app');
var Sync = require('ampersand-sync');
module.exports = View.extend({
template: require('../templates/views/validate.pug'),
render: function () {
this.renderWithTemplate(this);
this.validate();
return this;
},
validate: function () {
var self = this;
var payload = {
token: this.parent.token
};
var syncOptions = {
headers: App.me.ajaxConfig().headers,
url: App.apiUrl + '/user/confirm',
json: payload,
success: function () {
App.me.validated = true;
self.parent.stage = 'validated';
},
error: function () {
App.view.message = 'Invalid token';
}
};
Sync('create', null, syncOptions);
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/workout-activity-short.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var SuggestionView = require('./suggestion');
var SetView = View.extend({
template: require('../templates/views/set-short.pug'),
bindings: {
'model.formattedShort': {
type: 'text',
hook: 'set'
},
'model.pr': {
type: 'booleanClass',
hook: 'set',
class: 'pr'
}
}
});
module.exports = View.extend({
template: require('../templates/views/workout-activity-short.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'activity-name'
},
'model.historyUrl': {
type: 'attribute',
name: 'href',
hook: 'activity-name'
},
'model.comment': {
type: 'text',
hook: 'activity-comment'
},
'model.ready': {
type: 'toggle',
no: '[data-hook=new-activity]'
},
'model.hasSuggestions': {
type: 'toggle',
hook: 'has-suggestions'
},
'model.hasComment': {
type: 'toggle',
hook: 'toggle-comment'
}
},
events: {
'click [data-hook=new-activity]': 'findAlias'
},
render: function () {
this.renderWithTemplate(this);
this.renderSubview(new SuggestionView({ model: this.model }), this.queryByHook('new-confirm'));
this.renderCollection(this.model.sets, SetView, this.queryByHook('sets'));
this.renderCollection(this.model.suggestions, SuggestionView, this.queryByHook('suggestions'));
this.cacheElements({ aliasModal: '[data-hook=choose-alias]' });
$(this.el).foundation();
return this;
},
findAlias: function () {
$(this.aliasModal).foundation('reveal', 'open');
},
closeModal: function () {
$(this.aliasModal).foundation('reveal', 'close');
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/workout-activity.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var SetView = View.extend({
template: require('../templates/views/set.pug'),
bindings: {
'model.formattedFull': {
type: 'text',
hook: 'set'
},
'model.pr': {
type: 'booleanClass',
hook: 'set',
class: 'pr'
},
'model.hasComment': {
type: 'toggle',
hook: 'toggle-comment'
}
}
});
module.exports = View.extend({
template: require('../templates/views/workout-activity.pug'),
bindings: {
'model.displayName': {
type: 'text',
hook: 'activity-name'
},
'model.historyUrl': {
type: 'attribute',
name: 'href',
hook: 'activity-name'
},
'model.comment': {
type: 'text',
hook: 'activity-comment'
},
'model.hasComment': {
type: 'toggle',
hook: 'toggle-comment'
}
},
render: function () {
this.renderWithTemplate(this);
this.renderCollection(this.model.sets, SetView, this.queryByHook('sets'));
return this;
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/workout-share.js | JavaScript | 'use strict';
var View = require('ampersand-view');
var MarkdownActivityShortView = require('./markdown-activity-short');
var MarkdownActivityLongView = require('./markdown-activity-long');
var BBCodeActivityShortView = require('./bbcode-activity-short');
var BBCodeActivityLongView = require('./bbcode-activity-long');
module.exports = View.extend({
template: require('../templates/views/workout-share.pug'),
session: {
style: 'string'
},
initialize: function () {
this.style = 'markdown-short';
},
render: function () {
this.renderWithTemplate(this);
this.renderCollection(this.model.activities, MarkdownActivityShortView, this.queryByHook('activities-markdown-short'));
this.renderCollection(this.model.activities, MarkdownActivityLongView, this.queryByHook('activities-markdown-long'));
this.renderCollection(this.model.activities, BBCodeActivityShortView, this.queryByHook('activities-bbcode-short'));
this.renderCollection(this.model.activities, BBCodeActivityLongView, this.queryByHook('activities-bbcode-long'));
},
bindings: {
style: {
type: 'switch',
cases: {
'markdown-short': '[data-hook=markdown-short-share]',
'markdown-long': '[data-hook=markdown-long-share]',
'bbcode-short': '[data-hook=bbcode-short-share]',
'bbcode-long': '[data-hook=bbcode-long-share]'
}
},
'model.formattedDate': {
type: 'text',
hook: 'workout-date'
},
'model.name': {
type: 'text',
hook: 'workout-name'
},
'model.shareLink': [{
type: 'attribute',
hook: 'share-link',
name: 'href'
}, {
type: 'text',
hook: 'share-link'
}],
'model.canShare': [{
type: 'toggle',
hook: 'show-share-link'
}, {
type: 'toggle',
hook: 'no-share-link',
invert: true
}]
},
events: {
'click [name=share-style]': 'changeStyle'
},
changeStyle: function (e) {
this.style = e.target.value;
}
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
client/views/workout-summary.js | JavaScript | 'use strict';
var View = require('ampersand-view');
module.exports = View.extend({
bindings: {
'model.link': {
type: 'attribute',
hook: 'workout-name',
name: 'href'
},
'model.name': {
type: 'text',
hook: 'workout-name'
},
'model.date': {
type: 'text',
hook: 'workout-date'
},
'model.activityLabel': {
type: 'text',
hook: 'workout-activities'
}
},
template: require('../templates/views/workout-summary.pug')
});
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
configs/local.js | JavaScript | 'use strict';
//Config for local development
module.exports = {
DEV: true,
APIURL: 'http://localhost:3001',
ASSETSURL: 'http://localhost:8080',
PORTALURL: 'http://localhost:8080'
};
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
configs/production.js | JavaScript | 'use strict';
module.exports = {
APIURL: 'https://api.lift.zone',
ASSETSURL: 'https://assets.lift.zone',
PORTALURL: 'https://lift.zone'
};
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
configs/staging.js | JavaScript | 'use strict';
module.exports = {
APIURL: 'http://staging.api.lift.zone',
ASSETSURL: 'http://staging.assets.lift.zone',
PORTALURL: 'http://staging.lift.zone'
};
| wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
local/index.html | HTML | <!DOCTYPE html><html class="no-js" lang="en" dir="ltr"><head><title>lift.zone</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="http://localhost:8080/css/normalize.css"><link rel="stylesheet" href="http://localhost:8080/css/foundation.css"><link rel="stylesheet" href="http://localhost:8080/css/font-awesome.css"><script type="text/javascript" src="http://localhost:8080/js/vendor/modernizr.js"></script></head><body><div data-hook="app"><div><div class="contain-to-grid"><nav class="top-bar" data-topbar="data-topbar" role="navigation" data-hook="navigation"><ul class="title-area"><li class="name"><h1><a href="/">lift.zone</a></h1></li><li class="toggle-topbar menu-icon"><a href="#">Menu</a></li></ul><section class="top-bar-section"><ul class="right" data-hook="menu"><li class="has-dropdown"><a href="/workouts">Workouts</a><ul class="dropdown"><li><a href="/workouts/new">New</a></li></ul></li><li><a href="/activities">Activities</a></li><li><a href="/tools">Tools</a></li><li> </li><li><a class="button" href="/login" data-hook="nav-user-name">Log in</a></li><li data-hook="nav-admin" data-anddom-display="data-anddom-display" data-anddom-hidden="true" style="display: none;"><a href="/admin">Admin</a></li><li data-hook="nav-logout" data-anddom-display="data-anddom-display" data-anddom-hidden="true" style="display: none;"><a href="/logout">Logout</a></li></ul></section></nav></div><div class="alert-box info" data-hook="page-message" data-alert="data-alert" data-anddom-display="data-anddom-display" data-anddom-hidden="true" style="display: none;"></div><div data-hook="page-container"><section><div class="row"><div class="small-12 columns"><h1>Loading</h1></div><hr/></div></section></div><div class="row"><hr/><div class="left"><dl class="sub-nav" data-hook="navigation"><dd><a href="/privacy">Privacy</a></dd><dd><a href="/about">About</a></dd><dd><a href="/news">News</a></dd><dd><a href="https://twitter.com/wraithgar"><i class="fa fa-twitter"></i></a></dd></dl></div><div class="right"><dl class="sub-nav"><dd>© 2016 Michael Garvin</dd></dl></div></div></div><script type="text/javascript" src="http://localhost:8080/js/vendor/jquery.js"></script><script type="text/javascript" src="http://localhost:8080/js/vendor/foundation.js"></script><script type="text/javascript" src="http://localhost:8080/js/bundle.js"></script></div></body></html> | wraithgar/lift.zone | 0 | JavaScript | wraithgar | Gar | ||
moonbeams.js | JavaScript | 'use strict'
// Moonbeams.js
// (c) 2014 Michael Garvin
// Moonbeams may be freely distributed under the MIT license.
//
// Unless specifically stated otherwise, all julian days are in dynamical time
const Moonbeams = {}
module.exports = Moonbeams
// Data stores
// -----------
// mean equinox/solstice expression table for years -1000 to 1000
const meanSeasonTableA = [
[1721139.29189, 365242.13740, 0.06134, 0.00111, 0.00071],
[1721233.25401, 365241.72562, 0.05323, 0.00907, 0.00025],
[1721325.70455, 365242.49558, 0.11677, 0.00297, 0.00075],
[1721414.39987, 365242.88257, 0.00769, 0.00933, 0.00006]
]
// mean equinox/solstice expression table for years 1000 to 3000
const meanSeasonTableB = [
[2451623.80984, 365242.37404, 0.05169, 0.00411, 0.00057],
[2451716.56767, 365241.62603, 0.00325, 0.00888, 0.00030],
[2451810.21715, 365242.01767, 0.11575, 0.00337, 0.00078],
[2451900.05952, 365242.74049, 0.06223, 0.00823, 0.00032]
]
// Periodic terms for calculating solstice/equinox from mean
const periodicTermTableA = [
[485, 324.96, 1934.136],
[203, 337.23, 32964.467],
[199, 342.08, 20.186],
[182, 27.85, 445267.112],
[156, 73.14, 45036.886],
[136, 171.52, 22518.443],
[77, 222.54, 65928.934],
[74, 296.72, 3034.906],
[70, 243.58, 9037.513],
[58, 119.81, 33718.147],
[52, 297.17, 150.678],
[50, 21.02, 2281.226],
[45, 247.54, 29929.562],
[44, 325.15, 31555.956],
[29, 60.93, 4443.417],
[18, 155.12, 67555.328],
[17, 288.79, 4562.452],
[16, 198.04, 62894.029],
[14, 199.76, 31436.921],
[12, 95.39, 14577.848],
[12, 287.11, 31931.756],
[12, 320.81, 34777.259],
[9, 227.73, 1222.114],
[8, 15.45, 16859.074]
]
// Helper functions
// ----------------
// Convert decimal degrees to radians
Moonbeams.degreeToRadian = function (degrees) {
return degrees * Math.PI / 180
}
// Returns cosine of decimal degrees
const cosine = Moonbeams.cosone = function (degree) {
return Math.cos(Moonbeams.degreeToRadian(degree))
}
// Returns tangent of decimal degrees
Moonbeams.tangent = function (degree) {
return Math.tan(Moonbeams.degreeToRadian(degree))
}
// Returns INT of given decimal number
// INT is the integer portion *closest to zero*
// Meeus calls this INT so we do too
const INT = Moonbeams.INT = function (number) {
return Math[number < 0 ? 'ceil' : 'floor'](number)
}
// Returns julian cycle since Jan 1, 2000
// Meeus calls this T so we do too
const T = Moonbeams.T = function (jd) {
return (jd - 2451545.0) / 36525
}
// Converts given hours, minutes, and arcseconds right ascention
const hmsToRightAscention = Moonbeams.hmsToRightAscention = function (hours, minutes, arcseconds) {
return (hours + (minutes / 60) + (arcseconds / 3600)) * 15
}
Moonbeams.rightAscentionToHms = function (ra) {
const degrees = ra / 15
const hour = INT(degrees)
const minute = INT((degrees - hour) * 60.0)
const second = (((degrees - hour) * 60.0) - minute) * 60.0
return { hour: hour, minute: minute, second: second }
}
// Converts given hours, minutes, and seconds into decimal of a day
Moonbeams.hmsToDay = function (hours, minutes, seconds) {
return (hmsToRightAscention(hours, minutes, seconds) / 360)
}
// Converts given decimal day to hours, minutes, and (arc)seconds
Moonbeams.dayToHms = function (degree) {
// Return the hours, minutes, seconds from the decimal portion of given degree
const dayFragment = degree - INT(degree)
let hour = INT(dayFragment * 24.0)
let minute = INT((dayFragment * 24.0 - hour) * 60.0)
let second = ((dayFragment * 24.0 - hour) * 60.0 - minute) * 60.0
if (second > 59.999) {
second = 0
minute = minute + 1
}
if (minute > 59.999) {
minute = 0
hour = hour + 1
}
return { hour: hour, minute: minute, fullSecond: second, second: INT(second) }
}
// Returns true if given year is a leap year
const isLeapYear = Moonbeams.isLeapYear = function (year) {
if (year % 4 !== 0) {
// Not divisible by 4, common year
return false
}
if (year % 100 !== 0) {
return true
}
if (year % 400 !== 0) {
// Not divisible by 400, common year
return false
}
return true
}
// (Meeus chapter 12)
// Calculate mean sidereal time at Greenwich of a given julian day
Moonbeams.meanSiderealTime = function (jd) {
let mean
const cycle = T(jd)
mean = 280.46061837 +
(360.98564736629 * (jd - 2451545.0)) +
(0.000387933 * cycle * cycle) -
(cycle * cycle * cycle / 38710000)
if (mean < 0 || mean > 360) {
mean = mean - Math.floor(mean / 360) * 360
}
return mean
}
// (Meeus chapter 12)
// Calculate apparent sidereal time at Greenwich of a given julian day
Moonbeams.apparentSiderealTime = function (jd) {
// See chapter 22 for nutation
}
// Main conversion functions
// -------------------------
// (Meeus chapter 7)
// Convert given decimal julian day into calendar object
// with year, month, fullDay (decimal day), day (integer day), hour,
// minute, fullSecond (decimal second), second (integer second)
const jdToCalendar = Moonbeams.jdToCalendar = function (jd) {
if (jd < 0) {
throw new Error('Cannot convert from negative Julian Day numbers')
}
jd = jd + 0.5
const Z = INT(jd) // Integer part of jd
const F = jd - Z // Fractional (decimal) part of jd
let A = Z
if (Z >= 2299161) {
const alpha = INT((Z - 1867216.25) / 36524.25)
A = Z + 1 + alpha - INT(alpha / 4)
}
const B = A + 1524
const C = INT((B - 122.1) / 365.25)
const D = INT(365.25 * C)
const E = INT((B - D) / 30.6001)
// DAY
const day = B - D - INT(30.6001 * E) + F
// MONTH
let month
if (E < 14) {
month = E - 1
} else {
month = E - 13
}
// YEAR
let year
if (month > 2) {
year = C - 4716
} else {
year = C - 4715
}
const result = { year: year, month: month, day: day }
return result
}
// (Meeus chapter 7)
// Convert given year, month, day to decimal julian day
// Day can be decimal
// (Use hmsToDay if you have hours, minutes, and seconds to add to a day)
Moonbeams.calendarToJd = function (year, month, day) {
if (year < -4712) {
throw new Error('Cannot convert to negative Julian Day numbers')
}
if (month < 0 || month > 12) {
throw new Error('Month must be 1 through 12')
}
if (day < 0) {
throw new Error('Day must be positive')
}
if (month < 3) {
// Consider Jan and Feb to be month 13 and 14 of previous year
year = year - 1
month = month + 12
}
const A = INT(year / 100)
let B
// if we're before 10/15/1582 we're julian
if (
(year < 1582) ||
(year === 1582 && month < 10) ||
(year === 1582 && month === 10 && day < 15)
) {
B = 0
} else {
B = 2 - A + INT(A / 4)
}
const jd = INT(365.25 * (year + 4716)) +
INT(30.6001 * (month + 1)) +
day + B - 1524.5
return jd
}
// Calculation functions
// ---------------------
// (Meeus chapter 27)
// Calculate the mean equinox or solstice for a year
const meanSeason = Moonbeams.meanSeason = function (seasonIndex, year) {
if (year < -1000 || year > 3000) {
throw new Error('Can only calculate season for years between -1000 and 3000')
}
if (seasonIndex < 0 || seasonIndex > 3) {
throw new Error('seasonIndex must be one of: 0, 1, 2, 3')
}
let table
if (year > 1000) {
table = meanSeasonTableB[seasonIndex]
year = year - 2000
} else {
table = meanSeasonTableA[seasonIndex]
}
const Y = year / 1000
// TODO shorthand this
const jd = table[0] +
(table[1] * Y) +
(table[2] * Math.pow(Y, 2)) -
(table[3] * Math.pow(Y, 3)) -
(table[4] * Math.pow(Y, 4))
return jd
}
// (Meeus chapter 27)
// Calculate time of given equinox/solstice for a year
// seasonIndex can be
// 0 - March equinox
// 1 - June solstice
// 2 - September equinox
// 3 - December solstice
// Returns a julian day in dynamical time
Moonbeams.season = function (seasonIndex, year) {
const jde0 = meanSeason(seasonIndex, year)
const cycle = T(jde0)
const W = (35999.373 * cycle) - 2.47
const dl = 1 +
(0.0334 * cosine(W)) +
(0.0007 * cosine(W * 2))
let S = 0
for (let i = 0; i < 24; i++) {
S = S + periodicTermTableA[i][0] * cosine(periodicTermTableA[i][1] + (periodicTermTableA[i][2] * cycle))
}
const jde = jde0 + ((0.00001 * S) / dl)
return jde
}
// (Meeus chapter 7)
// Return day of week (0-6) of a given julian day
Moonbeams.dayOfWeek = function (jd) {
return (jd + 1.5) % 7
}
// (Meeus chapter 7)
// Return day of the year for given julian day
Moonbeams.dayOfYear = function (jd) {
const calendar = jdToCalendar(jd)
const leapYear = isLeapYear(calendar.year)
let K
if (leapYear) {
K = 1
} else {
K = 2
}
const N = INT((275 * calendar.month) / 9) - (K * INT((calendar.month + 9) / 12)) + calendar.day - 30
return N
}
// (Meeus chapter 7)
// Return calendar object for a given day of year
// Algorithm found by A. Pouplier, of the Société Astronomique do Liège, Belgium
Moonbeams.yearDayToCalendar = function (yearDay, year) {
const leapYear = isLeapYear(year)
let K
if (leapYear) {
K = 1
} else {
K = 2
}
let month
if (yearDay < 32) {
month = 1
} else {
month = INT(((9 * (K + yearDay)) / 275) + 0.98)
}
const day = yearDay - INT((275 * month) / 9) + (K * INT((month + 9) / 12)) + 30
return { year: year, month: month, day: day }
}
/*
// (Meeus chapter 15)
// Calculate the time of sunrise for a given julian day
Moonbeams.sunrise = function (jd, options) {
// var day;
const settings = {
latitude: 0, // Geographic latitude
longitude: 0,
dT: 0,
h0: -0.8333 // The Sun
}
if (options) {
Object.keys(options).forEach(function (optionName) {
settings[optionName] = options[optionName]
})
}
const calendar = jdToCalendar(jd)
// day = INT(calendar.day) + 0.5;
// Calculate sidereal time theta0 at 0h UT on day D for the meridian of greenwich, in degrees
const meanSidereal = meanSiderealTime(calendar.day)
// Calculate teh apparent right ascentions and eclinations of the sun
}
*/
| wraithgar/moonbeams | 2 | Astronomical calculations | JavaScript | wraithgar | Gar | |
test/index.js | JavaScript | 'use strict'
const Code = require('@hapi/code')
const Lab = require('@hapi/lab')
const Moonbeams = require('../')
const lab = exports.lab = Lab.script()
lab.experiment('Main conversion functions', function () {
// Test data from Meeus chapter 7
// year, month, decimal day, jd, hour, minute, second
const table = [
[1957, 10, 4.81, 2436116.31, 19, 26, 24],
[2000, 1, 1.5, 2451545.0, 12, 0, 0],
[1999, 1, 1, 2451179.5, 0, 0, 0],
[1987, 1, 27, 2446822.5, 0, 0, 0],
[1987, 6, 19.5, 2446966.0, 12, 0, 0],
[1988, 1, 27, 2447187.5, 0, 0, 0],
[1988, 6, 19.5, 2447332.0, 12, 0, 0],
[1900, 1, 1, 2415020.5, 0, 0, 0],
[1600, 1, 1, 2305447.5, 0, 0, 0],
[1600, 12, 31, 2305812.5, 0, 0, 0],
[837, 4, 10.3, 2026871.8, 7, 12, 0],
[333, 1, 27.5, 1842713, 12, 0, 0],
[-123, 12, 31, 1676496.5, 0, 0, 0],
[-122, 1, 1, 1676497.5, 0, 0, 0],
[-584, 5, 28.63, 1507900.13, 15, 7, 11],
[-1000, 7, 12.5, 1356001, 12, 0, 0],
[-1000, 2, 29, 1355866.5, 0, 0, 0],
[-1001, 8, 17.9, 1355671.4, 21, 36, 0],
[-4712, 1, 1.5, 0, 12, 0, 0]
]
lab.test('Julian Day to Calendar Date', function () {
table.forEach(function (testData) {
const result = Moonbeams.jdToCalendar(testData[3])
Code.expect(result, 'calendar date from julian day').to.include(['year', 'month', 'day'])
const hms = Moonbeams.dayToHms(result.day)
Code.expect(result.year, 'year from julian day ' + testData[3]).to.equal(testData[0])
Code.expect(result.month, 'month from julian day ' + testData[3]).to.equal(testData[1])
Code.expect(Moonbeams.INT(result.day), 'day from julian day ' + testData[3]).to.equal(Moonbeams.INT(testData[2]))
Code.expect(hms.hour, 'hour from julian day ' + testData[3]).to.equal(testData[4])
Code.expect(hms.minute, 'minute from julian day ' + testData[3]).to.equal(testData[5])
Code.expect(hms.second, 'second from julian day ' + testData[3]).to.equal(testData[6])
})
})
lab.test('Calendar Date to Julian Day', function () {
table.forEach(function (testData) {
const result = Moonbeams.calendarToJd(testData[0], testData[1], testData[2])
Code.expect(result, 'julian day from calendar date ' + testData[0] + '/' + testData[1] + '/' + testData[2]).to.equal(testData[3])
})
})
})
lab.experiment('season calculator', function () {
// Test data from Meeus chapter 27
// season, year, jd
const table = [
[1, 1962, 2437837.39245]
]
lab.test('Calculate julian day of season', function () {
table.forEach(function (testData) {
const result = Moonbeams.season(testData[0], testData[1])
Code.expect(Math.floor(result * 10000), 'julian day for ' + testData[0] + '/' + testData[1]).to.equal(Math.floor(testData[2] * 10000))
})
})
})
lab.experiment('helper functions', function () {
lab.test('INT', function () {
// Examples from Meeus chapter 7
// x, INT(x)
const table = [
[7 / 4, 1],
[8 / 4, 2],
[5.02, 5],
[5.9999, 5],
[-7.83, -7]
]
table.forEach(function (testData) {
const result = Moonbeams.INT(testData[0])
Code.expect(result, 'INT(' + testData[0] + ')').to.equal(testData[1])
})
})
lab.test('T', function () {
// jd, T(jd)
const table = [
[2446895.5, -12729637]
]
table.forEach(function (testData) {
const result = Moonbeams.T(testData[0])
Code.expect(Moonbeams.INT(result * 100000000), 'T(' + testData[0] + ')').to.equal(testData[1])
})
})
lab.test('hms to decimal day', function () {
// hour, minute, second, decimal day
const table = [
[12, 0, 0, 0.5],
[19, 26, 24, 0.81],
[18, 0, 0, 0.75],
[19, 21, 0, 0.80625] // Floating error test
]
table.forEach(function (testData) {
let result = Moonbeams.hmsToDay(testData[0], testData[1], testData[2])
Code.expect(result, 'decimal of ' + testData[0] + ' ' + testData[1] + ' ' + testData[2]).to.equal(testData[3])
result = Moonbeams.dayToHms(testData[3])
Code.expect(result, 'hms of ' + testData[3]).to.include(['hour', 'minute', 'second'])
Code.expect(result.hour, 'hour of ' + testData[3]).to.equal(testData[0])
Code.expect(result.minute, 'minute of ' + testData[3]).to.equal(testData[1])
Code.expect(result.second, 'second of ' + testData[3]).to.equal(testData[2])
})
})
lab.test('hms to right ascention', function () {
// hour, minute, second, right ascention
const table = [
[9, 14, 55.8, 138.73250] // Example 1.a from Meeus
]
table.forEach(function (testData) {
let result = Moonbeams.hmsToRightAscention(testData[0], testData[1], testData[2])
Code.expect(result, 'right ascention of' + testData[0] + ' ' + testData[1] + ' ' + testData[2]).to.equal(testData[3])
result = Moonbeams.rightAscentionToHms(testData[3])
Code.expect(result, 'hms of ' + testData[3]).to.include(['hour', 'minute', 'second'])
Code.expect(result.hour, 'hour of ' + testData[3]).to.equal(testData[0])
Code.expect(result.minute, 'minute of ' + testData[3]).to.equal(testData[1])
Code.expect(Math.floor(result.second), 'second of ' + testData[3]).to.equal(Math.floor(testData[2]))
})
})
lab.test('Leap year', function () {
// year, is leap year
const table = [
[900, false],
[1236, true],
[1429, false],
[750, false],
[1700, false],
[1800, false],
[1900, false],
[2100, false],
[1600, true],
[2000, true],
[2400, true]
]
table.forEach(function (testData) {
const result = Moonbeams.isLeapYear(testData[0])
Code.expect(result, 'year ' + testData[0]).to.equal(testData[1])
})
})
lab.test('Day of week', function () {
// jd, day of week
const table = [
[2434923.5, 3] // Example 7.e from Meeus
]
table.forEach(function (testData) {
const result = Moonbeams.dayOfWeek(testData[0])
Code.expect(result, 'day of week for julian day ' + testData[0]).to.equal(testData[1])
})
})
lab.test('Day of year', function () {
// year, month, day, day of year
const table = [
[1978, 11, 14, 318], // Example7.f from Meeus
[1988, 4, 22, 113] // Example7.g from Meeus
]
table.forEach(function (testData) {
const jd = Moonbeams.calendarToJd(testData[0], testData[1], testData[2])
let result = Moonbeams.dayOfYear(jd)
Code.expect(result, 'day of year for ' + testData[0] + '/' + testData[1] + '/' + testData[2]).to.equal(testData[3])
result = Moonbeams.yearDayToCalendar(testData[3], testData[0])
Code.expect(result, 'calendar date from day ' + testData[3] + ' of year ' + testData[0]).to.include(['year', 'month', 'day'])
Code.expect(result.year, 'year from day ' + testData[3] + ' of year ' + testData[0]).to.equal(testData[0])
Code.expect(result.month, 'month from day ' + testData[3] + ' of year ' + testData[0]).to.equal(testData[1])
Code.expect(result.day, 'month day from day ' + testData[3] + ' of year ' + testData[0]).to.equal(testData[2])
})
})
lab.test('Sidereal time', function () {
// jd, mean hour, mean minute, mean second, apparent hour, apparent minute, apparent second
const table = [
[2446895.5, 13, 10, 46.3668], // Example 12.a from Meeus
[2446896.30625, 8, 34, 57.0896] // Example 12.b from Meeus
]
table.forEach(function (testData) {
const result = Moonbeams.meanSiderealTime(testData[0])
const hms = Moonbeams.rightAscentionToHms(result)
Code.expect(hms.hour, 'mean sidereal hour of ' + testData[0]).to.equal(testData[1])
Code.expect(hms.minute, 'mean sidereal minute of ' + testData[0]).to.equal(testData[2])
Code.expect(Moonbeams.INT(hms.second * 100), 'mean sidereal second of ' + testData[0]).to.equal(Moonbeams.INT(testData[3] * 100))
})
})
})
lab.experiment('trig functions', function () {
lab.test('tangent', function () {
// Example 1.a from Meeus
const result = Moonbeams.tangent(138.73250)
Code.expect(Math.floor(result * 1000000)).to.equal(-877517)
})
})
| wraithgar/moonbeams | 2 | Astronomical calculations | JavaScript | wraithgar | Gar | |
bin/create_test_db.sh | Shell | #!/bin/sh
#Helper script to demonstrate how to quickly create the test db using the default values in the test fixtures
psql -d postgres -c "CREATE ROLE redcrab_test with password 'redcrab_test' nosuperuser nocreatedb nocreaterole inherit login"
createdb redcrab_test -O redcrab_test
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
lib/index.js | JavaScript | 'use strict';
const Sql = require('./sql');
const Fs = require('fs');
const Path = require('path');
const PG = require('pg-promise');
const YamlMigration = require('./yaml');
const internals = {};
internals.defaults = {
advisory_lock: 72656463726162, //unique number for advisory locks
schema_start: 10000, //first integer schema number to use
table_name: 'redcrab_migrations', //sql table in which to store migrations
template_directory: './templates', //schema template directory
migration_directory: './migrations' //db migration files directory
};
class Redcrab {
constructor(options) {
this.options = Object.assign({}, internals.defaults, options);
const { pg, connection, db } = this.options;
if (!db) {
const _pg = PG(pg);
this.db = _pg(connection);
} else {
this.db = db;
}
this.ready = this.setup();
}
/*
* Bootstrap the schema into the db
*/
async setup() {
const { migration_directory } = this.options;
await this.db.tx(async t => {
return t.batch([
t.query(Sql.getTxLock, this.options),
t.query(Sql.createTable, this.options)
]);
});
//Import migration files and insert new ones into the db
const filenames = await new Promise((resolve, reject) => {
Fs.readdir(migration_directory, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
});
const order_regex = /^[0-9]+/;
const inserts = [];
this.file_migrations = filenames.reduce((acc, filename) => {
if (filename.startsWith('.')) {
return acc;
}
if (!order_regex.test(filename)) {
throw new Error(
`Migration filenames must begin with an integer. Invalid filename "${filename}"`
);
}
let [order] = order_regex.exec(filename);
order = Number(order);
inserts.push(
this.db.query(Sql.insertMigration, { order, filename, ...this.options })
);
acc[order] = filename;
return acc;
}, {});
await Promise.all(inserts);
}
/*
* Sync file migrations into the db
* Basic migration validation (none missing, renamed)
* Return migration metadata (not actual contents)
*/
async getMigrations() {
const db_migrations = await this.db.query(Sql.getMigrations, this.options);
const forward = [];
const backward = [];
let next_order = 10000;
//look for db entries that don't have files, or the filename changed
for (const db_migration of db_migrations) {
next_order = db_migration.id + 1;
if (!this.file_migrations[db_migration.id]) {
throw new Error(
`Missing migration file "${db_migration.name}". Migrations db may be corrupt.`
);
}
if (this.file_migrations[db_migration.id] !== db_migration.name) {
throw new Error(
`Migration #${db_migration.id} has incorrect filename. Expected "${
db_migration.name
}" but found ${
this.file_migrations[db_migration.id]
}". Migrations db may be corrupt.`
);
}
if (db_migration.migrated_at) {
backward.push(db_migration);
} else {
forward.push(db_migration);
}
}
return { migrations: db_migrations, forward, backward, next_order };
}
/*
* Create a new migrations file
*/
async create(args) {
await this.ready;
const { name, type } = { type: 'yaml', name: 'migration', ...args };
const { template_directory, migration_directory } = this.options;
await new Promise((resolve, reject) => {
Fs.stat(Path.join(template_directory, type), (err, stats) => {
if (err) {
return reject(err);
}
if (!stats.isFile()) {
return reject(
new Error(
`"${type}" in "${template_directory}" is not a valid file`
)
);
}
return resolve();
});
});
const { next_order } = await this.getMigrations();
const filename = `${next_order}-${name}.${type}`;
//Only create the file, it will be picked up next time we run
return new Promise((resolve, reject) => {
Fs.copyFile(
Path.join(template_directory, type),
Path.join(migration_directory, filename),
err => {
// Coverage disabled for now due to the overhead required to get this to throw
// $lab:coverage:off$
if (err) {
return reject(err);
}
// $lab:coverage:on$
return resolve(filename);
}
);
});
}
async run({ migration, direction }) {
let runner;
const parts = Path.parse(migration.name);
if (parts.ext !== '.yaml' && parts.ext !== '.js') {
throw new Error(
`Invalid migration file "${migration.name}", that file type is not supported`
);
}
if (parts.ext === '.yaml') {
runner = new YamlMigration({
filename: migration.name,
...this.options
});
} else {
runner = require(Path.resolve(
this.options.migration_directory,
migration.name
));
}
return this.db.tx(async t => {
await runner[direction](t);
if (direction === 'forward') {
await t.query(Sql.markMigration, {
id: migration.id,
...this.options
});
} else {
await t.query(Sql.unmarkMigration, {
id: migration.id,
...this.options
});
}
});
}
//Migrate the db forward
async forward() {
await this.ready;
await this.db.task(async t => {
await t.query(Sql.getLock, this.options);
try {
const { forward } = await this.getMigrations();
for (const migration of forward) {
//These potentially run in a different connection
await this.run({ migration, direction: 'forward' });
}
} catch (e) {
await t.query(Sql.releaseLock, this.options);
throw e;
}
await t.query(Sql.releaseLock, this.options);
});
}
//Migrate the db backward
async backward() {
await this.ready;
await this.db.task(async t => {
await t.query(Sql.getLock, this.options);
try {
const { backward } = await this.getMigrations();
const migration = backward.pop();
if (migration) {
await this.run({ migration, direction: 'backward' });
}
} catch (e) {
await t.query(Sql.releaseLock, this.options);
throw e;
}
await t.query(Sql.releaseLock, this.options);
});
}
}
module.exports = Redcrab;
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
lib/sql.js | JavaScript | 'use strict';
exports.createTable = `
CREATE TABLE IF NOT EXISTS \${table_name#} (
id integer NOT NULL PRIMARY KEY,
name text,
migrated_at timestamp with time zone
);
`;
exports.insertMigration =
'INSERT INTO ${table_name#} (id, name) values (${order}, ${filename}) ON CONFLICT (id) DO NOTHING RETURNING *';
exports.getMigrations =
'SELECT id, name, migrated_at from ${table_name#} ORDER BY id';
exports.getTxLock = 'SELECT pg_advisory_xact_lock(${advisory_lock})';
exports.getLock = 'SELECT pg_advisory_lock(${advisory_lock})';
exports.releaseLock = 'SELECT pg_advisory_unlock(${advisory_lock})';
exports.markMigration =
'UPDATE ${table_name#} SET migrated_at=NOW() WHERE id=${id} RETURNING *';
exports.unmarkMigration =
'UPDATE ${table_name#} SET migrated_at=NULL WHERE id=${id} RETURNING *';
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
lib/yaml.js | JavaScript | 'use strict';
const Yaml = require('js-yaml');
const Fs = require('fs');
const Path = require('path');
class YamlMigration {
constructor({ filename, migration_directory }) {
const raw = Fs.readFileSync(
Path.join(migration_directory, filename),
'utf8'
);
const parsed = Yaml.safeLoad(raw);
this.data = parsed;
}
forward(db) {
if (this.data.forward) {
return db.query(this.data.forward);
}
}
backward(db) {
if (this.data.backward) {
return db.query(this.data.backward);
}
}
}
module.exports = YamlMigration;
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
migrations/10003-migration.js | JavaScript | 'use strict';
//$lab:coverage:off$
module.exports = {
description: 'Redcrab Migration',
forward: db => {
db.query('insert into foo (bar) values ($1)', ['baz']);
},
backward: db => {
db.query('delete from foo where bar = $1', ['baz']);
}
};
//$lab:coverage:on$
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
test/backward.js | JavaScript | 'use strict';
const Redcrab = require('../');
const Fixtures = require('./fixtures');
const Fs = require('fs');
const Path = require('path');
const lab = (exports.lab = require('@hapi/lab').script());
const { expect } = require('@hapi/code');
const { it, describe, beforeEach, after } = lab;
const { db, table_name } = Fixtures;
const defaults = { db, table_name };
describe('backward', () => {
beforeEach(async () => {
//Clean things up in case we exploded last time tests ran
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
after(async () => {
//Clean things up normally
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
it('migrates backward', async () => {
const r = new Redcrab({ ...defaults });
await r.forward();
await r.backward();
const rows_exist = await db.query('select * from ${table_name#}', {
table_name: 'foo'
});
expect(rows_exist.length).to.equal(0);
const { migrations } = await r.getMigrations();
for (const migration of migrations) {
if (migration.id < 10003) {
expect(migration.migrated_at).to.exist();
} else {
expect(migration.migrated_at).to.not.exist();
}
}
});
it('migrates all the way back, then one more', async () => {
const r = new Redcrab({ ...defaults });
await r.forward();
await r.backward(); //10003
await r.backward(); //10002
await r.backward(); //10001
await r.backward(); //10000
await r.backward(); //Nothing left, should not error
const table_exists = await db.query(
'select * from information_schema.tables where table_name=${table_name}',
{ table_name: 'foo' }
);
expect(table_exists.length).to.equal(0);
const { migrations } = await r.getMigrations();
for (const migration of migrations) {
expect(migration.migrated_at).to.not.exist();
}
});
it('invalid backward migration', { plan: 2 }, async () => {
await new Promise((resolve, reject) => {
Fs.writeFile(
Path.join('./migrations', '10004_bad_migration.yaml'),
'backward: this is not valid sql',
'utf8',
err => {
if (err) {
return reject(err);
}
return resolve();
}
);
});
const r = new Redcrab({ ...defaults });
await r.forward();
await r.backward().catch(e => {
expect(e).to.exist();
expect(e.message).to.include('syntax error');
});
});
});
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
test/concurrency.js | JavaScript | 'use strict';
const Redcrab = require('../');
const Fixtures = require('./fixtures');
const lab = (exports.lab = require('@hapi/lab').script());
const { expect } = require('@hapi/code');
const { it, describe, beforeEach, after } = lab;
const { db, table_name } = Fixtures;
const defaults = { db, table_name };
describe('concurrency', () => {
beforeEach(async () => {
//Clean things up in case we exploded last time tests ran
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
after(async () => {
//Clean things up normally
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
it(
"multiple instances don't collide with each other's setup",
{ plan: 5 },
async () => {
const redcrabs = [
new Redcrab(defaults),
new Redcrab(defaults),
new Redcrab(defaults),
new Redcrab(defaults),
new Redcrab(defaults)
];
for (const r of redcrabs) {
await r.ready;
expect(r).to.be.an.instanceof(Redcrab);
}
}
);
it("multiple instances don't collide with each other's forwards/backwards", async () => {
const redcrabs = [
new Redcrab(defaults),
new Redcrab(defaults),
new Redcrab(defaults),
new Redcrab(defaults),
new Redcrab(defaults)
];
for (let x = 1; x < 20; x++) {
const promises = [];
for (const r of redcrabs) {
if (Math.random() * 3 > 1) {
promises.push(r.backward());
} else {
promises.push(r.forward());
}
}
await Promise.all(promises);
}
expect(true).to.exist(); //We just have to get here.
});
});
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
test/create.js | JavaScript | 'use strict';
const Redcrab = require('../');
const Fixtures = require('./fixtures');
const Fs = require('fs');
const Path = require('path');
const lab = (exports.lab = require('@hapi/lab').script());
const { expect } = require('@hapi/code');
const { it, describe, beforeEach, before, after } = lab;
const { db, table_name } = Fixtures;
const defaults = { db, table_name };
describe('create', () => {
beforeEach(async () => {
//Clean things up in case we exploded last time tests ran
await Promise.all([
Fixtures.reset_db(),
Fixtures.reset_migrations('./migrations')
]);
});
after(async () => {
//Clean things up normally
await Promise.all([
Fixtures.reset_db(),
Fixtures.reset_migrations('./migrations')
]);
});
it('migration is created with defaults', async () => {
const r = new Redcrab(defaults);
const migration = await r.create();
expect(migration).to.exist();
expect(migration).to.startWith('10004');
expect(migration).to.endWith('.yaml');
const file = await Fixtures.migration_exists(migration);
expect(file).to.exist();
});
it('js migration is created', async () => {
const r = new Redcrab(defaults);
const migration = await r.create({ type: 'js' });
expect(migration).to.exist();
expect(migration).to.startWith('10004');
expect(migration).to.endWith('.js');
const file = await Fixtures.migration_exists(migration);
expect(file).to.exist();
});
it('named migration', async () => {
const r = new Redcrab(defaults);
const migration = await r.create({ name: 'test-migration' });
expect(migration).to.exist();
expect(migration).to.startWith('10004');
expect(migration).to.include('test-migration');
expect(migration).to.endWith('.yaml');
const file = await Fixtures.migration_exists(migration);
expect(file).to.exist();
});
it('invalid template directory', { plan: 2 }, async () => {
const r = new Redcrab({ ...defaults, template_directory: 'nonexistant' });
await r.create({ name: 'test-migration' }).catch(err => {
expect(err).to.exist();
expect(err.message).to.include('no such file or directory');
});
});
it('invalid template type', { plan: 2 }, async () => {
const r = new Redcrab(defaults);
await r.create({ type: 'nonexistant' }).catch(err => {
expect(err).to.exist();
expect(err.message).to.include('no such file or directory');
});
});
describe('template is not a file', () => {
before(async () => {
await new Promise((resolve, reject) => {
Fs.mkdir(Path.join('./templates', 'directory'), err => {
if (err) {
return reject(err);
}
return resolve();
});
});
});
after(async () => {
await new Promise((resolve, reject) => {
Fs.rmdir(Path.join('./templates', 'directory'), err => {
if (err) {
return reject(err);
}
return resolve();
});
});
});
it('errors', { plan: 2 }, async () => {
const r = new Redcrab(defaults);
await r.create({ type: 'directory' }).catch(err => {
expect(err).to.exist();
expect(err.message).to.include('not a valid file');
});
});
});
});
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
test/fixtures.js | JavaScript | 'use strict';
const PG = require('pg-promise');
const Fs = require('fs');
const Path = require('path');
//Coverage turned off because we don't iterate through any of the process.env stuff
/*$lab:coverage:off$*/
const table_name = process.env.REDCRAB_TEST_TABLE || 'redcrab_test';
exports.table_name = table_name;
const connection = process.env.REDCRAB_TEST_CONNECTION || {
database: process.env.REDCRAB_TEST_DATABASE || 'redcrab_test',
user: process.env.REDCRAB_TEST_USER || 'redcrab_test',
password: process.env.REDCRAB_TEST_PASSWORD || 'redcrab_test'
};
exports.connection = connection;
/*$lab:coverage:on$*/
const migration_directory = './migrations';
const pg = PG({});
const db = pg(connection);
exports.db = db;
exports.reset_db = async () => {
await db.task(t => {
return t.batch([
t.query('DROP TABLE IF EXISTS $1#', table_name),
t.query('DROP TABLE IF EXISTS $1#', 'foo')
]);
});
};
const migration_exists = async filename => {
return new Promise((resolve, reject) => {
Fs.stat(Path.join(migration_directory, filename), (err, stats) => {
if (err) {
return reject(err);
}
return resolve(stats);
});
});
};
exports.migration_exists = migration_exists;
const remove_file = async filename => {
return new Promise((resolve, reject) => {
return Fs.unlink(filename, err => {
if (err) {
return reject(err);
}
return resolve();
});
});
};
exports.remove_file = remove_file;
exports.reset_migrations = async () => {
await new Promise((resolve, reject) => {
Fs.readdir(migration_directory, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
}).then(async filenames => {
const order_regex = /^[0-9]+/;
for (const filename of filenames) {
if (filename === '.dotfile') {
continue;
}
if (!order_regex.test(filename)) {
await remove_file(Path.join(migration_directory, filename));
continue;
}
let [order] = order_regex.exec(filename);
if (order > 10003) {
await remove_file(Path.join(migration_directory, filename));
}
}
});
};
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
test/forward.js | JavaScript | 'use strict';
const Redcrab = require('../');
const Fixtures = require('./fixtures');
const Fs = require('fs');
const Path = require('path');
const lab = (exports.lab = require('@hapi/lab').script());
const { expect } = require('@hapi/code');
const { it, describe, beforeEach, before, after } = lab;
const { db, table_name } = Fixtures;
const defaults = { db, table_name };
describe('forward', () => {
beforeEach(async () => {
//Clean things up in case we exploded last time tests ran
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
after(async () => {
//Clean things up normally
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
it('migrates forward', async () => {
const r = new Redcrab({ ...defaults });
await r.forward();
const table_exists = await db.query(
'select * from information_schema.tables where table_name=${table_name}',
{ table_name: 'foo' }
);
expect(table_exists.length).to.equal(1);
const columns_exist = await db.query(
'select * from information_schema.columns where table_name=${table_name}',
{ table_name: 'foo' }
);
expect(columns_exist.length).to.equal(2);
const rows_exist = await db.query('select * from ${table_name#}', {
table_name: 'foo'
});
expect(rows_exist.length).to.equal(1);
const { migrations } = await r.getMigrations();
for (const migration of migrations) {
expect(migration.migrated_at).to.exist();
}
});
describe('invalid migration file', async () => {
before(async () => {
await new Promise((resolve, reject) => {
Fs.writeFile(
Path.join('./templates', 'txt'),
'Test txt template',
'utf8',
err => {
if (err) {
return reject(err);
}
return resolve();
}
);
});
});
after(async () => {
await new Promise((resolve, reject) => {
Fs.unlink(Path.join('./templates', 'txt'), err => {
if (err) {
return reject(err);
}
return resolve();
});
});
});
it('errors when migrating', { plan: 2 }, async () => {
let r = new Redcrab({ ...defaults });
await r.create({ type: 'txt' });
r = new Redcrab({ ...defaults });
await r.forward().catch(err => {
expect(err).to.exist();
expect(err.message).to.include('file type is not supported');
});
});
});
});
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
test/index.js | JavaScript | 'use strict';
const Redcrab = require('../');
const Fixtures = require('./fixtures');
const Sql = require('../lib/sql');
const Fs = require('fs');
const Path = require('path');
const lab = (exports.lab = require('@hapi/lab').script());
const { expect } = require('@hapi/code');
const { it, describe, beforeEach, after } = lab;
const { db, table_name } = Fixtures;
const defaults = { db, table_name };
describe('constructor', () => {
beforeEach(async () => {
//Clean things up in case we exploded last time tests ran
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
after(async () => {
//Clean things up normally
await Promise.all([Fixtures.reset_db(), Fixtures.reset_migrations()]);
});
it('migration dotfile exists', async () => {
//This file's existince is a test in and of itself, files like this should be ignored
const filename = await Fixtures.migration_exists('.dotfile');
expect(filename).to.exist();
});
it('instance created, and is ready', async () => {
const r = new Redcrab(defaults);
await r.ready;
expect(r).to.exist();
expect(r).to.be.an.instanceof(Redcrab);
});
it('connection failure', { plan: 1 }, () => {
const r = new Redcrab({
connection: {
database: 'should_not_exist',
username: 'mudcrab_fail',
password: 'nope'
}
});
return r.ready.catch(e => {
expect(e).to.exist();
});
});
it('throws on invalid migration directory', { plan: 1 }, () => {
const r = new Redcrab({ ...defaults, migration_directory: 'nonexistant' });
return r.ready.catch(e => {
expect(e.message).to.include('ENOENT');
});
});
it('invalid migration filename throws exception', { plan: 2 }, async () => {
await new Promise((resolve, reject) => {
Fs.writeFile(
Path.join('./migrations', 'no_number_filename.yaml'),
'description: no number in filename',
'utf8',
err => {
if (err) {
return reject(err);
}
return resolve();
}
);
});
const r = new Redcrab(defaults);
return r.ready.catch(e => {
expect(e).to.exist();
expect(e.message).to.include('Invalid filename');
});
});
it('migration in db but not on filesystem', async () => {
const r = new Redcrab(defaults);
await r.ready;
await db.query(Sql.insertMigration, {
table_name,
order: 10004,
filename: '10004_does_not_exist'
});
await r.create().catch(err => {
expect(err).to.exist();
expect(err.message).to.include('Missing migration file');
});
});
it('migration in db with wrong filename', async () => {
const r = new Redcrab(defaults);
await r.ready;
await db.query(
'UPDATE ${table_name#} set name = ${filename} where id = ${order}',
{ table_name, order: 10000, filename: '10000_wrong_filename' }
);
await r.create().catch(err => {
expect(err).to.exist();
expect(err.message).to.include('incorrect filename');
});
});
});
| wraithgar/redcrab | 1 | Postgresql migration library | JavaScript | wraithgar | Gar | |
index.html | HTML | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<title>TrophyIM Jabber Client</title>
<script type='text/javascript' src='trophyim.js'></script>
</head>
<body>
<div id='trophyimclient' />
</body>
</html>
| wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
json2.js | JavaScript | if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}})();
| wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
json_store.php | PHP | <?PHP
/** Basic JSON Store php script.
* You can use this if you have PHP installed, or implement your own.
*
* Note: this is only as secure as the session mechanism you use.
*
* TODO: define store interaction here
* update removes keys with null values
*/
session_start();
if ($_REQUEST['set']) {
$setArr = json_decode(stripslashes($_REQUEST['set']));
if ($setArr) {
foreach ($setArr as $key => $value) {
$_SESSION[$key] = $value;
}
print "OK";
} else {
print "Error " . $_REQUEST['set'];
}
} elseif ($_REQUEST['get']) {
foreach (split(",", $_REQUEST['get']) as $getvar) {
$return_array[$getvar] = $_SESSION[$getvar];
}
print json_encode($return_array);
} elseif ($_REQUEST['del']) {
foreach (split(",", $_REQUEST['del']) as $getvar) {
unset($_SESSION[$getvar]);
}
} else {
print "JSONStore";
}
| wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
soundmanager/soundmanager.js | JavaScript |
var isIE = navigator.appName.toLowerCase().indexOf('internet explorer')+1;
var isMac = navigator.appVersion.toLowerCase().indexOf('mac')+1;
function SoundManager(container) {
// DHTML-controlled sound via Flash
var self = this;
this.movies = []; // movie references
this.container = container;
this.unsupported = 0; // assumed to be supported
this.defaultName = 'default'; // default movie
this.FlashObject = function(url) {
var me = this;
this.o = null;
this.loaded = false;
this.isLoaded = function() {
if (me.loaded) return true;
if (!me.o) return false;
me.loaded = ((typeof(me.o.readyState)!='undefined' && me.o.readyState == 4) || (typeof(me.o.PercentLoaded)!='undefined' && me.o.PercentLoaded() == 100));
return me.loaded;
}
this.mC = document.createElement('div');
this.mC.className = 'movieContainer';
with (this.mC.style) {
// "hide" flash movie
position = 'absolute';
left = '-256px';
width = '64px';
height = '64px';
}
var html = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+url+'"><param name="quality" value="high"></object>','<embed src="'+url+'" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'];
if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
this.mC.innerHTML = html[0];
this.o = this.mC.getElementsByTagName('object')[0];
} else {
this.mC.innerHTML = html[1];
this.o = this.mC.getElementsByTagName('embed')[0];
}
document.getElementsByTagName('div')[0].appendChild(this.mC);
}
this.addMovie = function(movieName,url) {
self.movies[movieName] = new self.FlashObject(url);
}
this.checkMovie = function(movieName) {
movieName = movieName||self.defaultName;
if (!self.movies[movieName]) {
self.errorHandler('checkMovie','Exception: Could not find movie',arguments);
return false;
} else {
return (self.movies[movieName].isLoaded())?self.movies[movieName]:false;
}
}
this.errorHandler = function(methodName,message,oArguments,e) {
writeDebug('<div class="error">soundManager.'+methodName+'('+self.getArgs(oArguments)+'): '+message+(e?' ('+e.name+' - '+(e.message||e.description||'no description'):'')+'.'+(e?')':'')+'</div>');
}
this.play = function(soundID,loopCount,noDebug,movieName) {
if (self.unsupported) return false;
movie = self.checkMovie(movieName);
if (!movie) return false;
if (typeof(movie.o.TCallLabel)!='undefined') {
try {
self.setVariable(soundID,'loopCount',loopCount||1,movie);
movie.o.TCallLabel('/'+soundID,'start');
if (!noDebug) writeDebug('soundManager.play('+self.getArgs(arguments)+')');
} catch(e) {
self.errorHandler('play','Failed: Flash unsupported / undefined sound ID (check XML)',arguments,e);
}
}
}
this.stop = function(soundID,movieName) {
if (self.unsupported) return false;
movie = self.checkMovie(movieName);
if (!movie) return false;
try {
movie.o.TCallLabel('/'+soundID,'stop');
writeDebug('soundManager.stop('+self.getArgs(arguments)+')');
} catch(e) {
// Something blew up. Not supported?
self.errorHandler('stop','Failed: Flash unsupported / undefined sound ID (check XML)',arguments,e);
}
}
this.getArgs = function(params) {
var x = params?params.length:0;
if (!x) return '';
var result = '';
for (var i=0; i<x; i++) {
result += (i&&i<x?', ':'')+(params[i].toString().toLowerCase().indexOf('object')+1?typeof(params[i]):params[i]);
}
return result
}
this.setVariable = function(soundID,property,value,oMovie) {
// set Flash variables within a specific movie clip
if (!oMovie) return false;
try {
oMovie.o.SetVariable('/'+soundID+':'+property,value);
// writeDebug('soundManager.setVariable('+self.getArgs(arguments)+')');
} catch(e) {
// d'oh
self.errorHandler('setVariable','Failed',arguments,e);
}
}
this.setVariableExec = function(soundID,fromMethodName,oMovie) {
try {
oMovie.o.TCallLabel('/'+soundID,'setVariable');
} catch(e) {
self.errorHandler(fromMethodName||'undefined','Failed',arguments,e);
}
}
this.callMethodExec = function(soundID,fromMethodName,oMovie) {
try {
oMovie.o.TCallLabel('/'+soundID,'callMethod');
} catch(e) {
// Something blew up. Not supported?
self.errorHandler(fromMethodName||'undefined','Failed',arguments,e);
}
}
this.callMethod = function(soundID,methodName,methodParam,movieName) {
movie = self.checkMovie(movieName||self.defaultName);
if (!movie) return false;
self.setVariable(soundID,'jsProperty',methodName,movie);
self.setVariable(soundID,'jsPropertyValue',methodParam,movie);
self.callMethodExec(soundID,methodName,movie);
}
this.setPan = function(soundID,pan,movieName) {
self.callMethod(soundID,'setPan',pan,movieName);
}
this.setVolume = function(soundID,volume,movieName) {
self.callMethod(soundID,'setVolume',volume,movieName);
}
// constructor - create flash objects
if (isIE && isMac) {
this.unsupported = 1;
}
if (!this.unsupported) {
this.addMovie(this.defaultName,'soundcontroller.swf');
// this.addMovie('rc','rubber-chicken-audio.swf');
}
}
function SoundManagerNull() {
// Null object for unsupported case
this.movies = []; // movie references
this.container = null;
this.unsupported = 1;
this.FlashObject = function(url) {}
this.addMovie = function(name,url) {}
this.play = function(movieName,soundID) {
return false;
}
this.defaultName = 'default';
}
function writeDebug(msg) {
var o = document.getElementById('trophyimlog');
if (!o) return false;
var d = document.createElement('div');
d.innerHTML = msg;
o.appendChild(d);
}
var soundManager = null;
function soundManagerInit() {
soundManager = new SoundManager();
}
| wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
static.html | HTML | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<link rel='stylesheet' href='trophyim.css' type='text/css'\ media='screen' />
<title>Static TrophyIM page</title>
<body>
<div class="title"><div class="logo">TrophyIM - XMPP (Jabber) Javascript IM client</div></div>
<div id='trophyimclient'>
<div id='trophyimroster'>
<div class='trophyimrostergroup'>
<div class='trophyimrosterlabel'>Dudes</div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Bob</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Jim</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>
John Jacob Jingleheimer Schmidt
</div></div>
</div>
<div class='trophyimrostergroup'>
<div class='trophyimrosterlabel'>Guys named Steve</div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_aw'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_aw'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_aw'>
<div class='trophyimrostername'>Steve</div></div>
<div class='trophyimrosteritem trophyimrosteritem_aw'>
<div class='trophyimrostername'>Steve</div></div>
</div>
<div class='trophyimrostergroup'>
<div class='trophyimrosterlabel'>Girls</div>
<div class='trophyimrosteritem trophyimrosteritem_off'>
<div class='trophyimrostername'>Sue</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Jenny</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<!--
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
<div class='trophyimrosteritem trophyimrosteritem_av'>
<div class='trophyimrostername'>Martha</div></div>
-->
</div>
</div>
<div id='trophyimchat'>
<div id='trophyimchattabs'>
<div class='trophyimchattab trophyimchattab_f
trophyimchattab_av'>
<div class='trophyimtabclose'>x</div>
<div class='trophyimtabjid'>jid@domain.tld</div>
Steve</div>
<div class='trophyimchattab trophyimchattab_b
trophyimchattab_av'>
<div class='trophyimtabclose'>x</div>
<div class='trophyimtabjid'>jid@domain.tld</div>
Jim</div>
<div class='trophyimchattab trophyimchattab_a
trophyimchattab_av'>
<div class='trophyimtabclose'>x</div>
Bob</div>
<div class='trophyimchattab trophyimchattab_b
trophyimchattab_av'>
<div class='trophyimtabclose'>x</div>
Jenny</div>
<div class='trophyimchattab trophyimchattab_a
trophyimchattab_av'>
<div class='trophyimtabclose'>x</div>
Steve</div>
<div class='trophyimchattab trophyimchattab_b
trophyimchattab_off'>
<div class='trophyimtabclose'>x</div>
John Jacob Jingleheimer Schmidt
</div>
<div class='trophyimchattab trophyimchattab_b
trophyimchattab_aw'>
<div class='trophyimtabclose'>x</div>
Sue</div>
<div class='trophyimchattab trophyimchattab_b
trophyimchattab_aw'>
<div class='trophyimtabclose'>x</div>
Martha</div>
</div>
<div>
<div class='trophyimchatbox'>
<div class='trophyimchatmessage'>(Steve) Hello there how
are you today? Me, I am fine, thanks for asking!</div>
<div class='trophyimchatmessage'>(Me) Oh well I am ok too how nice of you to care. I am doing software programming. What are you up to?</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Steve) Hey</div>
<div class='trophyimchatmessage'>(Me) What?</div>
<div class='trophyimchatmessage'>(Steve) Nevermind</div>
</div>
<form name='chat'>
<textarea class='trophyimchatinput' rows='3' cols='50'></textarea>
<input type='button' value='Send' class="trophyimsend" />
</form>
</div>
</div>
<div id='trophyimstatus'>
<span>Status:</span>
<span id='trophyimstatuslist'>Select box</span><br />
<form><input type='button' value='disconnect' /></form>
</div>
</div>
<div id='trophyimlog'>
<div class='trophyimlogitem'>This is a log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This is another log message</div>
<div class='trophyimlogitem'>This<br />is<br />another<br />log<br
/>message</div>
<div class='trophyimlogitem'>This<br />is<br />another<br />log<br
/>message</div>
<div class='trophyimlogitem'>This<br />is<br />another<br />log<br
/>message</div>
</div>
</body>
</html>
| wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
trophyim.css | CSS | /*body, title, logo*/
body {
background-color:#9ca8bb;
font-family: Arial;
font-size: .8em;
}
.title{
background-color:#c0cbdb;
width:680px;
}
.logo{
background-image: url(trophyim.png);
background-repeat:no-repeat;
height: 57px;
width: 680px;
margin: 0 10px 0 0;
padding: 0;
text-indent:-9999px;
z-index:100;
}
/*primary div structure*/
#trophyimclient {
margin: 5px 0 0 0;
padding: 0;
max-width:700px;
}
#trophyimlogin {
text-align: center;
}
#trophyimroster {
width: 160px;
height: 445px;
overflow-y:scroll;
clear: none;
float: left;
background-color:white;
margin: 5px 0 0 0;
border-top: 1px #777 solid;
border-left: 1px #777 solid;
border-right: 4px #666 solid;
border-bottom: 4px #555 solid;
}
#trophyimchattabs {
width: 480px;
overflow-y:scroll;
font-size: .8em;
}
#trophyimchat {
height:435px;
background-color:white;
clear: right;
float: left;
margin: 5px 0 0 10px;
padding: 10px 10px 0 10px;
border-top: 1px #777 solid;
border-left: 1px #777 solid;
border-right: 4px #666 solid;
border-bottom: 4px #555 solid;
}
#trophyimstatus {
width: 180px;
padding:10px 5px 5px 10px;
clear: both;
}
#trophyimstatusselect {
}
#trophyimstatustext {
}
#trophyimstatusbutton {
}
#trophyimlog {
margin:20px 0 0 0;
width: 680px;
height: 300px;
overflow: auto;
background-color:#eee;
}
/*im friend roster*/
.trophyimrostername {
padding: 1px 3px 1px 3px;
font-size: .8em;
}
.trophyimrostergroup {
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 4px #999 solid;
border-bottom: 4px #999 solid;
padding: 5px;
/* padding:0 5px 10px 5px; */
margin: 10px 5px 10px 10px;
background-color:#eee;
}
.trophyimrosterlabel {
color: #346185;
font-size: 1em;
font-weight: bold;
padding: 0 0 5px 0;
}
.trophyimrosterjid {
/*hide jabber id from roster listing*/
display: none;
}
/*im friend roster statuses*/
.trophyimrosteritem {
border: 1px #666 solid;
}
.trophyimrosteritem_av { /*Available*/
color: #000000;
background-color:#a4ff9a;
font-weight:bold;
}
.trophyimrosteritem_aw { /*Away*/
color: #555;
background-color:#fbffbf;
}
.trophyimrosteritem_xa { /* Extended Away */
color: #555;
color: #ff9933;
}
.trophyimrosteritem_dnd { /* Do Not Disturb */
color: #000000;
background-color:ff3333;
}
.trophyimrosteritem_off { /*Offline*/
display: none;
color: #333;
font-style: italic;
background-color:#ccc;
}
/*im open tabs*/
.trophyimtabclose {
background-color:#ccc;
color: #000000;
font-size: 8px;
text-align: right;
cursor: default;
float: right;
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 2px #888 solid;
border-bottom: 2px #888 solid;
margin-left: 1px;
padding: 0 2px 1px 2px;
line-height:90%;
font-family: Arial;
font-weight:bold;
}
.trophyimtabclose:active {
border-bottom: 1px #ccc solid;
border-right: 1px #ccc solid;
border-left: 2px #888 solid;
border-top: 2px #888 solid;
}
.trophyimchattabjid {
/*hide jabber id from open tab listing*/
display: none;
}
.trophyimchattab {
clear: none;
float: left;
cursor: pointer;
height:12px;
width:102px;
padding:3px;
line-height:140%;
word-break: break-all;
overflow:hidden;
}
.trophyimchattabname {
margin-right: 1px;
padding: 2px;
}
/*im open tab statuses & position*/
.trophyimchattab_f { /*Foreground*/
margin:1px;
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 2px #999 solid;
border-bottom: 2px #999 solid;
background-color:#d1e5ff;
}
.trophyimchattab_b { /*Background*/
margin: 2px;
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 2px #999 solid;
border-bottom: 2px #999 solid;
}
.trophyimchattab_a { /*Alert (background/has new message)*/
margin: 2px;
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 2px #999 solid;
border-bottom: 2px #999 solid;
color:black;
font-weight:bold;
background-color:#ffd677;
}
.trophyimchattab_av { /*Available*/
margin: 2px;
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 2px #999 solid;
border-bottom: 2px #999 solid;
color: #000000;
}
.trophyimchattab_aw { /*Away*/
margin: 2px;
border-top: 1px #ccc solid;
border-left: 1px #ccc solid;
border-right: 2px #999 solid;
border-bottom: 2px #999 solid;
color: #777;
background-color:#eee;
}
.trophyimchattab_off { /*Offline*/
color: #333;
background-color:#ccc;
font-style: italic;
}
/*im chat area*/
.trophyimchatbox { /*Collection of chat messages*/
height: 300px;
width: 480px;
overflow-y: scroll;
}
.trophyimchatmessage { /*Each individual chat message*/
white-space: pre-wrap;
padding:5px;
width: 450px;
border-top: 1px dotted #ddd;
border-bottom: 1px solid #e7eafb;
background-image: url(textbg.png);
background-repeat: repeat-x;
background-position: bottom;
background-color:white;
}
textarea.trophyimchatinput {
}
/*log*/
.trophyimlogitem {
border-bottom: 1px #ccc dotted;
padding:5px;
} | wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
trophyim.js | JavaScript | /*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2008 Michael Garvin
*/
/*TODO dump / very loose roadmap
--0.4
add chats to json store
Mouseover status messages in roster
rosterClick shouldn't call makeChat if it doesn't have to
HTML in messages (xslt?)
Select presence status/message
Optional user-specified resource
Loglevel select on login instead of check box
vcard support http://xmpp.org/extensions/xep-0153.html
Notifications of closed chats
Notifications of typing
--0.5
roster management
figure out how we want to handle presence from our own jid (and transports)
roster sorting by presence / offline roster capablility
auto-subscribe vs prompted subscribe based on config option
--1.0 (or whenever someone submits better .css)
layout overhaul
code cleanup (like checking for excessive function lengths)
roster versioning http://xmpp.org/extensions/attic/xep-0237-0.1.html
make sure onload bootstrapping actually preserves existing onloads
*/
var TROPHYIM_BOSH_SERVICE = '/proxy/xmpp-httpbind'; //Change to suit
var TROPHYIM_LOG_LINES = 200;
var TROPHYIM_LOGLEVEL = 1; //0=debug, 1=info, 2=warn, 3=error, 4=fatal
var TROPHYIM_VERSION = "0.3";
var SOUNDON = true;
//Uncomment to make session reattachment work
//var TROPHYIM_JSON_STORE = "json_store.php";
/** File: trophyimclient.js
* A JavaScript front-end for strophe.js
*
* This is a JavaScript library that runs on top of strophe.js. All that
* is required is that your page have a <div> element with an id of
* 'trophyimclient', and that your page does not explicitly set an onload
* event in its <body> tag. In that case you need to append TrophyIM.load()
* to it.
*
* The style of the client can be conrolled via trophyim.css, which is
* auto-included by the client.
*/
/** Object: HTMLSnippets
*
* This is the repository for all the html snippets that TrophyIM uses
*
*/
HTMLSnippets = {
cssLink :
"<link rel='stylesheet' href='trophyim.css' type='text/css'\
media='screen' />",
loginPage : "<div id='trophyimlogin'>\
<form name='cred'><label for='trophyimjid'>JID:</label>\
<input type='text' id='trophyimjid' /><br />\
<label for='trophyimpass'>Password:</label>\
<input type='password' id='trophyimpass' /><br />\
<label for='trophyimloglevel'>Logging</label>\
<input type='checkbox' id='trophyimloglevel' /><br />\
<select id='trophyimstatusselect'>\
<option value='online'>online</option>\
<option value='chat'>willing to chat</option>\
<option value='away'>away</option>\
<option value='xa'>not available</option>\
<option value='dnd'>do not disturb</option>\
<option value='offline'>offline</option>\
</select>\
<input id='trophyimstatustext' type='text'/>\
<input id='trophyimstatusbutton' type='button' value='set' \
onclick='TrophyIM.updatePresence()'/></form></div>",
loggingDiv : "<div id='trophyimlog' />",
rosterDiv : "<div id='trophyimroster' />",
rosterGroup : "<div class='trophyimrostergroup'>\
<div class='trophyimrosterlabel' /></div>",
rosterItem : "<div class='trophyimrosteritem'\
onclick='TrophyIM.rosterClick(this)'><div class='trophyimrosterjid' />\
<div class='trophyimrostername' /></div>",
statusDiv : "<div id='trophyimstatus'><span>Status:</span>\
<form>\
<select id='trophyimstatusselect'>\
<option value='online'>online</option>\
<option value='chat'>willing to chat</option>\
<option value='away'>away</option>\
<option value='xa'>not available</option>\
<option value='dnd'>do not disturb</option>\
<option value='offline'>offline</option>\
</select>\
<input id='trophyimstatustext' type='text'/>\
<input id='trophyimstatusbutton' type='button' value='set'\
onclick='TrophyIM.updatePresence()'/>\
</form></div>",
chatArea : "<div id='trophyimchat'><div id='trophyimchattabs' /></div>",
chatBox : "<div><div class='trophyimchatbox' />\
<form name='chat' onsubmit='TrophyIM.sendMessage(this); return(false);'>\
<input type='text' class='trophyimchatinput' />\
<input type='button' value='Send' onclick='TrophyIM.sendMessage(this)' />\
</form></div>",
chatTab :
"<div class='trophyimchattab' onclick='TrophyIM.tabClick(this);'>\
<div class='trophyimchattabjid' /><div class='trophyimtabclose'\
onclick='TrophyIM.tabClose(this);'>x</div>\
<div class='trophyimchattabname' />\
</div>"
};
/** Object: DOMObjects
* This class contains builders for all the DOM objects needed by TrophyIM
*/
DOMObjects = {
/** Function: xmlParse
* Cross-browser alternative to using innerHTML
* Parses given string, returns valid DOM HTML object
*
* Parameters:
* (String) xml - the xml string to parse
*/
xmlParse : function(xmlString) {
var xmlObj = this.xmlRender(xmlString);
if(xmlObj) {
try { //Firefox, Gecko, etc
if (this.processor == undefined) {
this.processor = new XSLTProcessor();
this.processor.importStylesheet(this.xmlRender(
'<xsl:stylesheet version="1.0"\
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\
<xsl:output method="html" indent="yes"/><xsl:template\
match="@*|node()"><xsl:copy><xsl:copy-of\
select="@*|node()"/></xsl:copy></xsl:template>\
</xsl:stylesheet>'));
}
var htmlObj =
this.processor.transformToDocument(xmlObj).documentElement;
//Safari has a quirk where it wraps dom elements in <html><body>
if (htmlObj.tagName.toLowerCase() == 'html') {
htmlObj = htmlObj.firstChild.firstChild;
}
return document.importNode(htmlObj, true);
} catch(e) {
try { //IE is so very very special
var htmlObj = document.importNode(xmlObj.documentElement, true);
if (htmlObj.tagName.toLowerCase() == "div") {
var div_wrapper = document.createElement('div');
div_wrapper.appendChild(htmlObj);
if(div_wrapper.innerHTML) {
div_wrapper.innerHTML = div_wrapper.innerHTML;
}
htmlObj = div_wrapper.firstChild;
}
return htmlObj;
} catch(e) {
alert(
"TrophyIM Error: Cannot add html to page" + e.message);
}
}
}
},
/** Function: xmlRender
* Uses browser-specific methods to turn given string into xml object
*
* Parameters:
* (String) xml - the xml string to parse
*/
xmlRender : function(xmlString) {
try {//IE
var renderObj = new ActiveXObject("Microsoft.XMLDOM");
renderObj.async="false";
if(xmlString) {
renderObj.loadXML(xmlString);
}
} catch (e) {
try { //Firefox, Gecko, etc
if (this.parser == undefined) {
this.parser = new DOMParser();
}
var renderObj = this.parser.parseFromString(xmlString,
"application/xml");
} catch(e) {
alert("TrophyIM Error: Cannot create new html for page");
}
}
return renderObj;
},
/** Function: getHTML
* Returns named HTML snippet as DOM object
*
* Parameters:
* (String) name - name of HTML snippet to retrieve (see HTMLSnippets
* object)
*/
getHTML : function(page) {
return this.xmlParse(HTMLSnippets[page]);
},
/** Function: getScript
* Returns script object with src to given script
*
* Parameters:
* (String) script - name of script to put in src attribute of script
* element
*/
getScript : function(script) {
var newscript = document.createElement('script');
newscript.setAttribute('src', script);
newscript.setAttribute('type', 'text/javascript');
return newscript;
}
};
/** Object: TrophyIM
*
* This is the actual TrophyIM application. It searches for the
* 'trophyimclient' element and inserts itself into that.
*/
TrophyIM = {
/** Constants:
*
* (Boolean) stale_roster - roster is stale and needs to be rewritten.
* (Boolean) focus - whether or not client has focus
*/
constants : {stale_roster: false, focus: true},
/** Object: chatHistory
*
* Stores chat history (last 10 message) and current presence of active
* chat tabs. Indexed by jid.
*/
chatHistory : {},
/** Object: activeChats
*
* This object stores the currently active chats.
*/
activeChats : {current: null, divs: {}},
/** Function: setCookie
*
* Sets cookie name/value pair. Date and path are auto-selected.
*
* Parameters:
* (String) name - the name of the cookie variable
* (String) value - the value of the cookie variable
*/
setCookie : function(name, value) {
var expire = new Date();
expire.setDate(expire.getDate() + 365);
document.cookie = name + "=" + value + "; expires=" + expire.toGMTString();
},
/** Function: delCookie
*
* Deletes cookie
*
* Parameters:
* (String) name) - the name of the cookie to delete
*/
delCookie : function(name) {
var expire = new Date();
expire.setDate(expire.getDate() - 365);
document.cookie = name + "= ; expires=" + expire.toGMTString();
delete TrophyIM.cookies[name];
},
/** Function: getCookies
*
* Retrieves all trophyim cookies into an indexed object. Inteneded to be
* called once, at which time the app refers to the returned object instead
* of re-parsing the cookie string every time.
*
* Each cookie is also re-applied so as to refresh the expiry date.
*/
getCookies : function() {
var cObj = {};
var cookies = document.cookie.split(';');
for (var c in cookies) {
while (cookies[c].charAt(0)==' ') {
cookies[c] = cookies[c].substring(1,cookies[c].length);
}
if (cookies[c].substr(0, 8) == "trophyim") {
var nvpair = cookies[c].split("=", 2);
cObj[nvpair[0]] = nvpair[1];
TrophyIM.setCookie(nvpair[0], nvpair[1]);
}
}
return cObj;
},
/** Function: load
*
* This function searches for the trophyimclient div and loads the client
* into it.
*/
load : function() {
TrophyIM.cookies = TrophyIM.getCookies();
var client_div = document.getElementById('trophyimclient');
if (client_div) {
TrophyIM.client_div = client_div;
//load .css
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getHTML('cssLink'));
//Load other .js scripts needed
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getScript('soundmanager/soundmanager.js'));
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getScript('strophejs/strophe.js'));
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getScript('strophejs/md5.js'));
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getScript('strophejs/sha1.js'));
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getScript('strophejs/b64.js'));
document.getElementsByTagName('head')[0].appendChild(
DOMObjects.getScript('json2.js')); //Keep this script last
//Wait a second to give scripts time to load
setTimeout("TrophyIM.initSound()", 250);
setTimeout("TrophyIM.showLogin()", 500);
} else {
alert("Cannot load TrophyIM client.\nClient div not found.");
}
},
/** Function: storeData
*
* Store all our data in the JSONStore, if it is active
*/
storeData : function() {
if (TrophyIM.connection && TrophyIM.connection.connected) {
TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
TrophyIM.connection.sid + "|" + TrophyIM.connection.rid);
TrophyIM.rosterObj.save();
}
},
/** Function: showlogin
*
* This function clears out the IM box and either redisplays the login
* page, or re-attaches to Strophe, preserving the logging div if it
* exists, or creating a new one of we are re-attaching.
*/
showLogin : function() {
//JSON is the last script to load, so we wait on it
//Added Strophe check too because of bug where it's sometimes missing
if (typeof(JSON) != undefined && typeof(Strophe) != undefined &&
typeof(soundManagerInit) != undefined) {
soundManagerInit();
TrophyIM.JSONStore = new TrophyIMJSONStore();
if (TrophyIM.JSONStore.store_working && TrophyIM.cookies['trophyim_bosh_xid']) {
var xids = TrophyIM.cookies['trophyim_bosh_xid'].split("|");
TrophyIM.delCookie('trophyim_bosh_xid');
TrophyIM.constants.stale_roster = true;
if (TrophyIM.cookies['trophyimloglevel']) {
TrophyIM.client_div.appendChild(DOMObjects.getHTML('loggingDiv'));
TrophyIM.logging_div = document.getElementById('trophyimlog');
}
TrophyIM.connection = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
TrophyIM.connection.rawInput = TrophyIM.rawInput;
TrophyIM.connection.rawOutput = TrophyIM.rawOutput;
Strophe.log = TrophyIM.log;
Strophe.info('Attempting Strophe attach.');
TrophyIM.connection.attach(xids[0], xids[1], xids[2],
TrophyIM.onConnect);
TrophyIM.onConnect(Strophe.Status.CONNECTED);
} else {
var logging_div = TrophyIM.clearClient();
TrophyIM.client_div.appendChild(DOMObjects.getHTML('loginPage'));
if(logging_div) {
TrophyIM.client_div.appendChild(logging_div);
TrophyIM.logging_div =
document.getElementById('trophyimlog');
}
if (TrophyIM.cookies['trophyimjid']) {
document.getElementById('trophyimjid').value =
TrophyIM.cookies['trophyimjid'];
}
if (TrophyIM.cookies['trophyimloglevel']) {
document.getElementById('trophyimloglevel').checked = true;
}
}
} else {
setTimeout("TrophyIM.showLogin()", 500);
}
},
/** Function: log
*
* This function logs the given message in the trophyimlog div
*
* Parameter: (String) msg - the message to log
*/
log : function(level, msg) {
if (TrophyIM.logging_div && level >= TROPHYIM_LOGLEVEL) {
while(TrophyIM.logging_div.childNodes.length > TROPHYIM_LOG_LINES) {
TrophyIM.logging_div.removeChild(
TrophyIM.logging_div.firstChild);
}
var msg_div = document.createElement('div');
msg_div.className = 'trophyimlogitem';
msg_div.appendChild(document.createTextNode(msg));
TrophyIM.logging_div.appendChild(msg_div);
TrophyIM.logging_div.scrollTop = TrophyIM.logging_div.scrollHeight;
}
},
/** Function: rawInput
*
* This logs the packets actually recieved by strophe at the debug level
*/
rawInput : function (data) {
Strophe.debug("RECV: " + data);
},
/** Function: rawInput
*
* This logs the packets actually recieved by strophe at the debug level
*/
rawOutput : function (data) {
Strophe.debug("SEND: " + data);
},
/** Function: updatePresence
*
* This function update the status, changing the presence (online,
* offline, away...), and/or updating the status message. It may call login
* of logout if such status are selected.
*/
updatePresence : function() {
TrophyIM.mypresence = {resource:null, priority:null, show:null, status:null};
TrophyIM.mypresence['show'] = document.getElementById('trophyimstatusselect').value;
TrophyIM.mypresence['status'] = document.getElementById('trophyimstatustext').value;
if (TrophyIM.mypresence['status'] == "") TrophyIM.mypresence['status'] = null;
if ((TrophyIM.mypresence['show'] != "offline") &&
((!TrophyIM.connection) ||
(TrophyIM.connection.connected == false))) {
if (TrophyIM.mypresence['show'] == "online") TrophyIM.mypresence['show']=null;
TrophyIM.login();
} else if ((TrophyIM.mypresence['show'] == "offline") &&
((TrophyIM.connection != null) &&
(TrophyIM.connection.connected == true))) {
TrophyIM.logout();
} else if ((TrophyIM.connection != null) &&
(TrophyIM.connection.connected == true)) {
presence = $pres()
if (TrophyIM.mypresence['show']) {
presence.c('show').t(TrophyIM.mypresence['show']).up()
}
if (TrophyIM.mypresence['status']) {
presence.c('status').t(TrophyIM.mypresence['status']).up()
}
TrophyIM.connection.send(presence.tree());
}
},
/** Function: login
*
* This function logs into server using information given on login page.
* Since the login page is where the logging checkbox is, it makes or
* removes the logging div and cookie accordingly.
*
*/
login : function() {
if (document.getElementById('trophyimloglevel').checked) {
TrophyIM.setCookie('trophyimloglevel', 1);
if (!document.getElementById('trophyimlog')) {
TrophyIM.client_div.appendChild(DOMObjects.getHTML('loggingDiv'));
TrophyIM.logging_div = document.getElementById('trophyimlog');
}
} else {
TrophyIM.delCookie('trophyimloglevel');
if (document.getElementById('trophyimlog')) {
TrophyIM.client_div.removeChild(document.getElementById(
'trophyimlog'));
TrophyIM.logging_div = null;
}
}
if (TrophyIM.JSONStore.store_working) { //In case they never logged out
TrophyIM.JSONStore.delData(['groups','roster', 'active_chat',
'chat_history']);
}
TrophyIM.connection = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
TrophyIM.connection.rawInput = TrophyIM.rawInput;
TrophyIM.connection.rawOutput = TrophyIM.rawOutput;
Strophe.log = TrophyIM.log;
var barejid = document.getElementById('trophyimjid').value
var fulljid = barejid + '/TrophyIM';
TrophyIM.setCookie('trophyimjid', barejid);
var password = document.getElementById('trophyimpass').value;
TrophyIM.connection.connect(fulljid, password, TrophyIM.onConnect);
},
/** Function: login
*
* Logs into fresh session through Strophe, purging any old data.
*/
logout : function() {
TrophyIM.delCookie('trophyim_bosh_xid');
delete TrophyIM['cookies']['trophyim_bosh_xid'];
if (TrophyIM.JSONStore.store_working) {
TrophyIM.JSONStore.delData(['groups','roster', 'active_chat',
'chat_history']);
}
for (var chat in TrophyIM.activeChats['divs']) {
delete TrophyIM.activeChats['divs'][chat];
}
TrophyIM.activeChats = {current: null, divs: {}},
TrophyIM.connection.disconnect();
TrophyIM.showLogin();
},
/** Function onConnect
*
* Callback given to Strophe upon connection to BOSH proxy.
*/
onConnect : function(status) {
if (status == Strophe.Status.CONNECTING) {
Strophe.info('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
Strophe.info('Strophe failed to connect.');
TrophyIM.delCookie('trophyim_bosh_xid');
TrophyIM.showLogin();
} else if (status == Strophe.Status.DISCONNECTING) {
Strophe.info('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
Strophe.info('Strophe is disconnected.');
TrophyIM.delCookie('trophyim_bosh_xid');
TrophyIM.showLogin();
} else if (status == Strophe.Status.CONNECTED) {
Strophe.info('Strophe is connected.');
TrophyIM.showClient();
}
},
/** Function: showClient
*
* This clears out the main div and puts in the main client. It also
* registers all the handlers for Strophe to call in the client.
*/
showClient : function() {
TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
TrophyIM.connection.sid + "|" + TrophyIM.connection.rid);
var logging_div = TrophyIM.clearClient();
TrophyIM.client_div.appendChild(DOMObjects.getHTML('rosterDiv'));
TrophyIM.client_div.appendChild(DOMObjects.getHTML('chatArea'));
TrophyIM.client_div.appendChild(DOMObjects.getHTML('statusDiv'));
if(logging_div) {
TrophyIM.client_div.appendChild(logging_div);
TrophyIM.logging_div = document.getElementById('trophyimlog');
}
TrophyIM.rosterObj = new TrophyIMRoster();
TrophyIM.connection.addHandler(TrophyIM.onVersion, Strophe.NS.VERSION,
'iq', null, null, null);
TrophyIM.connection.addHandler(TrophyIM.onRoster, Strophe.NS.ROSTER,
'iq', null, null, null);
TrophyIM.connection.addHandler(TrophyIM.onPresence, null, 'presence',
null, null, null);
TrophyIM.connection.addHandler(TrophyIM.onMessage, null, 'message',
null, null, null);
//Get roster.
TrophyIM.connection.send($iq({type: 'get', xmlns: Strophe.NS.CLIENT}).c(
'query', {xmlns: Strophe.NS.ROSTER}).tree());
if (TrophyIM.mypresence['show']) {
var selectbox = document.getElementById('trophyimstatusselect');
for (var i=0; i<selectbox.options.length; i++) {
if (selectbox.options[i].value == TrophyIM.mypresence['show']) {
selectbox.options[i].selected = 'true';
}
}
}
TrophyIM.renderChats();
setTimeout("TrophyIM.renderRoster()", 1000);
},
/** Function: clearClient
*
* Clears out client div, preserving and returning existing logging_div if
* one exists
*/
clearClient : function() {
if(TrophyIM.logging_div) {
var logging_div = TrophyIM.client_div.removeChild(
document.getElementById('trophyimlog'));
} else {
var logging_div = null;
}
while(TrophyIM.client_div.childNodes.length > 0) {
TrophyIM.client_div.removeChild(TrophyIM.client_div.firstChild);
}
return logging_div;
},
/** Function: onVersion
*
* jabber:iq:version query handler
*/
onVersion : function(msg) {
Strophe.debug("Version handler");
if (msg.getAttribute('type') == 'get') {
var from = msg.getAttribute('from');
var to = msg.getAttribute('to');
var id = msg.getAttribute('id');
var reply = $iq({type: 'result', to: from, from: to, id: id}).c('query',
{name: "TrophyIM", version: TROPHYIM_VERSION, os:
"Javascript-capable browser"});
TrophyIM.connection.send(reply.tree());
}
return true;
},
/** Function: onRoster
*
* Roster iq handler
*/
onRoster : function(msg) {
Strophe.debug("Roster handler");
var roster_items = msg.firstChild.getElementsByTagName('item');
for (var i = 0; i < roster_items.length; i++) {
var groups = roster_items[i].getElementsByTagName('group');
var group_array = new Array();
if (groups.length == 0) {
group_array[group_array.length] = "";
}
for (var g = 0; g < groups.length; g++) {
group_array[group_array.length] =
groups[g].firstChild.nodeValue;
}
TrophyIM.rosterObj.addContact(roster_items[i].getAttribute('jid'),
roster_items[i].getAttribute('subscription'),
roster_items[i].getAttribute('name'), group_array);
}
if (msg.getAttribute('type') == 'set') {
TrophyIM.connection.send($iq({type: 'reply', id:
msg.getAttribute('id'), to: msg.getAttribute('from')}).tree());
}
/* now that we got the roster, update our presence (avoids duplicate
entries if we receive presence before getting the roster) */
TrophyIM.updatePresence();
return true;
},
/** Function: onPresence
*
* Presence handler
*/
onPresence : function(msg) {
Strophe.debug("Presence handler");
var type = msg.getAttribute('type') ? msg.getAttribute('type') :
'available';
var show = msg.getElementsByTagName('show').length ? Strophe.getText(
msg.getElementsByTagName('show')[0]) : type;
var status = msg.getElementsByTagName('status').length ? Strophe.getText(
msg.getElementsByTagName('status')[0]) : '';
var priority = msg.getElementsByTagName('priority').length ? parseInt(
Strophe.getText(msg.getElementsByTagName('priority')[0])) : 0;
TrophyIM.rosterObj.setPresence(msg.getAttribute('from'), priority,
show, status);
return true;
},
/** Function: onMessage
*
* Message handler
*/
onMessage : function(msg) {
Strophe.debug("Message handler");
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
var elems = msg.getElementsByTagName('body');
if ((type == 'chat' || type == 'normal') && elems.length > 0) {
var barejid = Strophe.getBareJidFromJid(from);
var jid_lower = barejid.toLowerCase();
var contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact'];
if (contact) { //Do we know you?
if (contact['name'] != null) {
message = contact['name'] + " (" + barejid + "): ";
} else {
message = contact['jid'] + ": ";
}
message += Strophe.getText(elems[0]);
TrophyIM.makeChat(from); //Make sure we have a chat window
TrophyIM.addMessage(message, jid_lower);
TrophyIM.alertSound('notify');
if (TrophyIM.activeChats['current'] != jid_lower) {
TrophyIM.activeChats['divs'][jid_lower][
'tab'].className = "trophyimchattab trophyimchattab_a";
TrophyIM.setTabPresence(from,
TrophyIM.activeChats['divs'][jid_lower]['tab']);
}
}
}
return true;
},
/** Function: initSound
*
* This function sets up the onblur and onfocus handlers that alert
* TrophyIM as to when the client does or doesn't have focus. Focus status
* is stored in TrophyIM.constants.has_focus
*/
initSound : function() {
//FIXME make sure we're not clobbering an existing
//window/document.onblur/focus
if (SOUNDON == true) {
Strophe.debug("Sound on");
window.onblur = function() {
TrophyIM.constants.has_focus = false;
}
window.onfocus = function() {
TrophyIM.constants.has_focus = true;
}
document.onblur = window.onblur;
document.focus = window.focus;
}
},
/** Function: alertSound
*
* Plays alert sound upon receipt of new message.
*
* Parameters:
* (String) sound - name of sound as defined in
* soundmanager/sound-config.xml
*/
alertSound : function(sound) {
if (TrophyIM.constants.has_focus == false) {
soundManager.play(sound);
}
},
/** Function: makeChat
*
* Make sure chat window to given fulljid exists, switching chat context to
* given resource
*/
makeChat : function(fulljid) {
var barejid = Strophe.getBareJidFromJid(fulljid);
if (!TrophyIM.activeChats['divs'][barejid]) {
var chat_tabs = document.getElementById('trophyimchattabs');
var chat_tab = DOMObjects.getHTML('chatTab');
var chat_box = DOMObjects.getHTML('chatBox');
var contact = TrophyIM.rosterObj.getContact(barejid);
var tab_name = (contact['name'] != null) ? contact['name'] : barejid;
chat_tab.className = "trophyimchattab trophyimchattab_a";
getElementsByClassName('trophyimchattabjid', 'div',
chat_tab)[0].appendChild(document.createTextNode(barejid));
getElementsByClassName('trophyimchattabname', 'div',
chat_tab)[0].appendChild(document.createTextNode(tab_name));
chat_tab = chat_tabs.appendChild(chat_tab);
TrophyIM.activeChats['divs'][barejid] = {jid:fulljid, tab:chat_tab,
box:chat_box};
if (!TrophyIM.activeChats['current']) { //We're the first
TrophyIM.activeChats['current'] = barejid;
document.getElementById('trophyimchat').appendChild(chat_box);
TrophyIM.activeChats['divs'][barejid]['box'] = chat_box;
TrophyIM.activeChats['divs'][barejid]['tab'].className =
"trophyimchattab trophyimchattab_f";
}
if (!TrophyIM.chatHistory[barejid.toLowerCase()]) {
TrophyIM.chatHistory[barejid.toLowerCase()] = {resource: null,
history: new Array()};
}
TrophyIM.setTabPresence(fulljid, chat_tab);
}
TrophyIM.activeChats['divs'][barejid.toLowerCase()]['resource'] =
Strophe.getResourceFromJid(fulljid);
TrophyIM.chatHistory[barejid.toLowerCase()]['resource'] =
Strophe.getResourceFromJid(fulljid);
},
/** Function showChat
*
* Make chat box to given barejid active
*/
showChat : function(barejid) {
if (TrophyIM.activeChats['current'] &&
TrophyIM.activeChats['current'] != barejid) {
var chat_area = document.getElementById('trophyimchat');
var active_divs =
TrophyIM.activeChats['divs'][TrophyIM.activeChats['current']];
active_divs['box'] =
chat_area.removeChild(getElementsByClassName('trophyimchatbox',
'div', chat_area)[0].parentNode);
active_divs['tab'].className = "trophyimchattab trophyimchattab_b";
TrophyIM.setTabPresence(TrophyIM.activeChats['current'],
active_divs['tab']);
TrophyIM.activeChats['divs'][barejid]['box'] =
chat_area.appendChild(TrophyIM.activeChats['divs'][barejid]['box']);
TrophyIM.activeChats['current'] = barejid;
TrophyIM.activeChats['divs'][barejid]['tab'].className =
"trophyimchattab trophyimchattab_f";
TrophyIM.setTabPresence(barejid,
TrophyIM.activeChats['divs'][barejid]['tab']);
getElementsByClassName('trophyimchatinput', null,
TrophyIM.activeChats['divs'][barejid]['box'])[0].focus();
}
},
/** Function: setTabPresence
*
* Applies appropriate class to tab div based on presence
*
* Parameters:
* (String) jid - jid to check presence for
* (String) tab_div - tab div element to alter class on
*/
setTabPresence : function(jid, tab_div) {
var presence = TrophyIM.rosterObj.getPresence(jid);
tab_div.className = tab_div.className.replace(" trophyimchattab_av", "");
tab_div.className = tab_div.className.replace(" trophyimchattab_aw", "");
tab_div.className = tab_div.className.replace(" trophyimchattab_off", "");
if (presence) {
if (presence['show'] == "chat" || presence['show'] == "available") {
tab_div.className += " trophyimchattab_av";
} else {
tab_div.className += " trophyimchattab_aw";
}
} else {
tab_div.className += " trophyimchattab_off";
}
},
/** Function: addMessage
*
* Adds message to chat box, and history
*
* Parameters:
* (string) msg - the message to add
* (string) jid - the jid of chat box to add the message to.
*/
addMessage : function(msg, jid) {
var chat_box = getElementsByClassName('trophyimchatbox', 'div',
TrophyIM.activeChats['divs'][jid]['box'])[0];
var msg_div = document.createElement('div');
msg_div.className = 'trophyimchatmessage';
msg_div.appendChild(document.createTextNode(msg));
chat_box.appendChild(msg_div);
chat_box.scrollTop = chat_box.scrollHeight;
if (TrophyIM.chatHistory[jid]['history'].length > 10) {
TrophyIM.chatHistory[jid]['history'].shift();
}
TrophyIM.chatHistory[jid]['history'][
TrophyIM.chatHistory[jid]['history'].length] = msg;
},
/** Function: renderRoster
*
* Renders roster, looking only for jids flagged by setPresence as having
* changed.
*/
renderRoster : function() {
if (TrophyIM.rosterObj.changes.length > 0) {
var roster_div = document.getElementById('trophyimroster');
if(roster_div) {
var groups = new Array();
for (var group in TrophyIM.rosterObj.groups) {
groups[groups.length] = group;
}
groups.sort();
var group_divs = getElementsByClassName('trophyimrostergroup',
null, roster_div);
for (var g = 0; g < group_divs.length; g++) {
var group_name = getElementsByClassName('trophyimrosterlabel',
null, group_divs[g])[0].firstChild.nodeValue;
while (group_name > groups[0]) {
var new_group = TrophyIM.renderGroup(groups[0], roster_div);
new_group = roster_div.insertBefore(new_group,
group_divs[g]);
if (TrophyIM.rosterObj.groupHasChanges(groups[0])) {
TrophyIM.renderGroupUsers(new_group, groups[0],
TrophyIM.rosterObj.changes.slice());
}
groups.shift();
}
if (group_name == groups[0]) {
groups.shift();
}
if (TrophyIM.rosterObj.groupHasChanges(group_name)) {
TrophyIM.renderGroupUsers(group_divs[g], group_name,
TrophyIM.rosterObj.changes.slice());
}
}
while (groups.length) {
var group_name = groups.shift();
var new_group = TrophyIM.renderGroup(group_name,
roster_div);
new_group = roster_div.appendChild(new_group);
if (TrophyIM.rosterObj.groupHasChanges(group_name)) {
TrophyIM.renderGroupUsers(new_group, group_name,
TrophyIM.rosterObj.changes.slice());
}
}
}
TrophyIM.rosterObj.changes = new Array();
TrophyIM.constants.stale_roster = false;
}
setTimeout("TrophyIM.renderRoster()", 1000);
},
/** Function: renderChats
*
* Renders chats found in TrophyIM.chatHistory. Called upon page reload.
* Waits for stale_roster flag to clear before trying to run, so that the
* roster exists
*/
renderChats : function() {
if (TrophyIM.constants.stale_roster == false) {
if(TrophyIM.JSONStore.store_working) {
var data = TrophyIM.JSONStore.getData(['chat_history',
'active_chat']);
if (data['active_chat']) {
for (var jid in data['chat_history']) {
fulljid = jid + "/" + data['chat_history'][jid]['resource'];
Strophe.info("Makechat " + fulljid);
TrophyIM.makeChat(fulljid);
for (var h = 0; h <
data['chat_history'][jid]['history'].length; h++) {
TrophyIM.addMessage(data['chat_history'][jid]['history'][h],
jid);
}
}
TrophyIM.chat_history = data['chat_history'];
TrophyIM.showChat(data['active_chat']);
}
}
} else {
setTimeout("TrophyIM.renderChats()", 1000);
}
},
/** Function: renderGroup
*
* Renders actual group label in roster
*
* Parameters:
* (String) group - name of group to render
* (DOM) roster_div - roster div
*
* Returns:
* DOM group div to append into roster
*/
renderGroup : function(group, roster_div) {
var new_group = DOMObjects.getHTML('rosterGroup');
var label_div = getElementsByClassName( 'trophyimrosterlabel', null,
new_group)[0];
label_div.appendChild(document.createTextNode(group));
new_group.appendChild(label_div);
return new_group;
},
/** Function: renderGroupUsers
*
* Re-renders user entries in given group div based on status of roster
*
* Parameter: (Array) changes - jids with changes in the roster. Note:
* renderGroupUsers will clobber this.
*/
renderGroupUsers : function(group_div, group_name, changes) {
var group_members = TrophyIM.rosterObj.groups[group_name];
var member_divs = getElementsByClassName('trophyimrosteritem', null,
group_div);
for (var m = 0; m < member_divs.length; m++) {
member_jid = getElementsByClassName('trophyimrosterjid', null,
member_divs[m])[0].firstChild.nodeValue;
if (member_jid > changes[0]) {
if (changes[0] in group_members) {
var new_presence = TrophyIM.rosterObj.getPresence(
changes[0]);
if(new_presence) {
var new_member = DOMObjects.getHTML('rosterItem');
var new_contact =
TrophyIM.rosterObj.getContact(changes[0]);
getElementsByClassName('trophyimrosterjid', null,
new_member)[0].appendChild(document.createTextNode(
changes[0]));
var new_name = (new_contact['name'] != null) ?
new_contact['name'] : changes[0];
getElementsByClassName('trophyimrostername', null,
new_member)[0].appendChild(document.createTextNode(
new_name));
group_div.insertBefore(new_member, member_divs[m]);
if (new_presence['show'] == "available" ||
new_presence['show'] == "chat") {
new_member.className =
"trophyimrosteritem trophyimrosteritem_av";
} else {
new_member.className =
"trophyimrosteritem trophyimrosteritem_aw";
}
} else {
//show offline contacts
}
}
changes.shift();
} else if (member_jid == changes[0]) {
member_presence = TrophyIM.rosterObj.getPresence(member_jid);
if(member_presence) {
if (member_presence['show'] == "available" ||
member_presence['show'] == "chat") {
member_divs[m].className =
"trophyimrosteritem trophyimrosteritem_av";
} else {
member_divs[m].className =
"trophyimrosteritem trophyimrosteritem_aw";
}
} else {
//show offline status
group_div.removeChild(member_divs[m]);
}
changes.shift();
}
}
while (changes.length > 0) {
if (changes[0] in group_members) {
var new_presence = TrophyIM.rosterObj.getPresence(changes[0]);
if(new_presence) {
var new_member = DOMObjects.getHTML('rosterItem');
var new_contact =
TrophyIM.rosterObj.getContact(changes[0]);
getElementsByClassName('trophyimrosterjid', null,
new_member)[0].appendChild(document.createTextNode(
changes[0]));
var new_name = (new_contact['name'] != null) ?
new_contact['name'] : changes[0];
getElementsByClassName('trophyimrostername', null,
new_member)[0].appendChild(document.createTextNode(
new_name));
group_div.appendChild(new_member);
if (new_presence['show'] == "available" ||
new_presence['show'] == "chat") {
new_member.className =
"trophyimrosteritem trophyimrosteritem_av";
} else if (new_presence['show'] == "away") {
new_member.className =
"trophyimrosteritem trophyimrosteritem_aw";
} else if (new_presence['show'] == "xa") {
new_member.className =
"trophyimrosteritem trophyimrosteritem_xa";
} else if (new_presence['show'] == "dnd") {
new_member.className =
"trophyimrosteritem trophyimrosteritem_dnd";
} else {
new_member.className =
"trophyimrosteritem trophyimrosteritem_off";
}
} else {
//show offline
}
}
changes.shift();
}
},
/** Function: rosterClick
*
* Handles actions when a roster item is clicked
*/
rosterClick : function(roster_item) {
var barejid = getElementsByClassName('trophyimrosterjid', null,
roster_item)[0].firstChild.nodeValue;
TrophyIM.makeChat(barejid);
TrophyIM.showChat(barejid);
},
/** Function: tabClick
*
* Handles actions when a chat tab is clicked
*/
tabClick : function(tab_item) {
var barejid = getElementsByClassName('trophyimchattabjid', null,
tab_item)[0].firstChild.nodeValue;
if (TrophyIM.activeChats['divs'][barejid]) {
TrophyIM.showChat(barejid);
}
},
/** Function: tabClose
*
* Closes chat tab
*/
tabClose : function(tab_item) {
var barejid = getElementsByClassName('trophyimchattabjid', null,
tab_item.parentNode)[0].firstChild.nodeValue;
if (TrophyIM.activeChats['current'] == barejid) {
if (tab_item.parentNode.nextSibling) {
TrophyIM.showChat(getElementsByClassName('trophyimchattabjid',
null, tab_item.parentNode.nextSibling)[0].firstChild.nodeValue);
} else if (tab_item.parentNode.previousSibling) {
TrophyIM.showChat(getElementsByClassName('trophyimchattabjid',
null, tab_item.parentNode.previousSibling)[0].firstChild.nodeValue);
} else { //no other active chat
document.getElementById('trophyimchat').removeChild(
getElementsByClassName('trophyimchatbox')[0].parentNode);
delete TrophyIM.activeChats['current'];
}
}
delete TrophyIM.activeChats['divs'][barejid];
delete TrophyIM.chatHistory[barejid];
//delete tab
tab_item.parentNode.parentNode.removeChild(tab_item.parentNode);
},
/** Function: sendMessage
*
* Send message from chat input to user
*/
sendMessage : function(chat_box) {
var message_input =
getElementsByClassName('trophyimchatinput', null,
chat_box.parentNode)[0];
var active_jid = TrophyIM.activeChats['current'];
if(TrophyIM.activeChats['current']) {
var active_chat =
TrophyIM.activeChats['divs'][TrophyIM.activeChats['current']];
var to = TrophyIM.activeChats['current'];
if (active_chat['resource']) {
to += "/" + active_chat['resource'];
}
TrophyIM.connection.send($msg({to: to, from:
TrophyIM.connection.jid, type: 'chat'}).c('body').t(
message_input.value).tree());
TrophyIM.addMessage("Me:\n" + message_input.value,
TrophyIM.activeChats['current']);
}
message_input.value = '';
message_input.focus();
}
};
/** Class: TrophyIMRoster
*
*
* This object stores the roster and presence info for the TrophyIMClient
*
* roster[jid_lower]['contact']
* roster[jid_lower]['presence'][resource]
*/
function TrophyIMRoster() {
/** Constants: internal arrays
* (Object) roster - the actual roster/presence information
* (Object) groups - list of current groups in the roster
* (Array) changes - array of jids with presence changes
*/
if (TrophyIM.JSONStore.store_working) {
var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
this.roster = (data['roster'] != null) ? data['roster'] : {};
this.groups = (data['groups'] != null) ? data['groups'] : {};
} else {
this.roster = {};
this.groups = {};
}
this.changes = new Array();
if (TrophyIM.constants.stale_roster) {
for (var jid in this.roster) {
this.changes[this.changes.length] = jid;
}
}
/** Function: addContact
*
* Adds given contact to roster
*
* Parameters:
* (String) jid - bare jid
* (String) subscription - subscription attribute for contact
* (String) name - name attribute for contact
* (Array) groups - array of groups contact is member of
*/
this.addContact = function(jid, subscription, name, groups) {
var contact = {jid:jid, subscription:subscription, name:name, groups:groups}
var jid_lower = jid.toLowerCase();
if (this.roster[jid_lower]) {
this.roster[jid_lower]['contact'] = contact;
} else {
this.roster[jid_lower] = {contact:contact};
}
groups = groups ? groups : [''];
for (var g = 0; g < groups.length; g++) {
if (!this.groups[groups[g]]) {
this.groups[groups[g]] = {};
}
this.groups[groups[g]][jid_lower] = jid_lower;
}
}
/** Function: getContact
*
* Returns contact entry for given jid
*
* Parameter: (String) jid - jid to return
*/
this.getContact = function(jid) {
if (this.roster[jid.toLowerCase()]) {
return this.roster[jid.toLowerCase()]['contact'];
}
}
/** Function: setPresence
*
* Sets presence
*
* Parameters:
* (String) fulljid: full jid with presence
* (Integer) priority: priority attribute from presence
* (String) show: show attribute from presence
* (String) status: status attribute from presence
*/
this.setPresence = function(fulljid, priority, show, status) {
var barejid = Strophe.getBareJidFromJid(fulljid);
var resource = Strophe.getResourceFromJid(fulljid);
var jid_lower = barejid.toLowerCase();
if(show != 'unavailable') {
if (!this.roster[jid_lower]) {
this.addContact(barejid, 'not-in-roster');
}
var presence = {
resource:resource, priority:priority, show:show, status:status
}
if (!this.roster[jid_lower]['presence']) {
this.roster[jid_lower]['presence'] = {}
}
this.roster[jid_lower]['presence'][resource] = presence
} else if (this.roster[jid_lower] && this.roster[jid_lower]['presence']
&& this.roster[jid_lower]['presence'][resource]) {
delete this.roster[jid_lower]['presence'][resource];
}
this.addChange(jid_lower);
if (TrophyIM.activeChats['divs'][jid_lower]) {
TrophyIM.setTabPresence(jid_lower,
TrophyIM.activeChats['divs'][jid_lower]['tab']);
}
}
/** Function: addChange
*
* Adds given jid to this.changes, keeping this.changes sorted and
* preventing duplicates.
*
* Parameters
* (String) jid : jid to add to this.changes
*/
this.addChange = function(jid) {
for (var c = 0; c < this.changes.length; c++) {
if (this.changes[c] == jid) {
return;
}
}
this.changes[this.changes.length] = jid;
this.changes.sort();
}
/** Function: getPresence
*
* Returns best presence for given jid as Array(resource, priority, show,
* status)
*
* Parameter: (String) fulljid - jid to return best presence for
*/
this.getPresence = function(fulljid) {
var jid = Strophe.getBareJidFromJid(fulljid);
var current = null;
if (this.roster[jid.toLowerCase()] &&
this.roster[jid.toLowerCase()]['presence']) {
for (var resource in this.roster[jid.toLowerCase()]['presence']) {
var presence = this.roster[jid.toLowerCase()]['presence'][resource];
if (current == null) {
current = presence
} else {
if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
|| presence['show'] == "available") || (current['show'] != "chat" ||
current['show'] != "available"))) {
current = presence
}
}
}
}
return current;
}
/** Function: groupHasChanges
*
* Returns true if current group has members in this.changes
*
* Parameters:
* (String) group - name of group to check
*/
this.groupHasChanges = function(group) {
for (var c = 0; c < this.changes.length; c++) {
if (this.groups[group][this.changes[c]]) {
return true;
}
}
return false;
}
/** Fuction: save
*
* Saves roster data to JSON store
*/
this.save = function() {
if (TrophyIM.JSONStore.store_working) {
TrophyIM.JSONStore.setData({roster:this.roster,
groups:this.groups, active_chat:TrophyIM.activeChats['current'],
chat_history:TrophyIM.chatHistory});
}
}
}
/** Class: TrophyIMJSONStore
*
*
* This object is the mechanism by which TrophyIM stores and retrieves its
* variables from the url provided by TROPHYIM_JSON_STORE
*
*/
function TrophyIMJSONStore() {
this.store_working = false;
/** Function _newXHR
*
* Set up new cross-browser xmlhttprequest object
*
* Parameters:
* (function) handler = what to set onreadystatechange to
*/
this._newXHR = function (handler) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
/** Function getData
* Gets data from JSONStore
*
* Parameters:
* (Array) vars = Variables to get from JSON store
*
* Returns:
* Object with variables indexed by names given in parameter 'vars'
*/
this.getData = function(vars) {
if (typeof(TROPHYIM_JSON_STORE) != undefined) {
Strophe.debug("Retrieving JSONStore data");
var xhr = this._newXHR();
var getdata = "get=" + vars.join(",");
try {
xhr.open("POST", TROPHYIM_JSON_STORE, false);
} catch (e) {
Strophe.error("JSONStore open failed.");
return false;
}
xhr.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', getdata.length);
xhr.send(getdata);
if (xhr.readyState == 4 && xhr.status == 200) {
try {
var dataObj = JSON.parse(xhr.responseText);
return this.emptyFix(dataObj);
} catch(e) {
Strophe.error("Could not parse JSONStore response" +
xhr.responseText);
return false;
}
} else {
Strophe.error("JSONStore open failed. Status: " + xhr.status);
return false;
}
}
}
/** Function emptyFix
* Fix for bugs in external JSON implementations such as
* http://bugs.php.net/bug.php?id=41504.
* A.K.A. Don't use PHP, people.
*/
this.emptyFix = function(obj) {
if (typeof(obj) == "object") {
for (var i in obj) {
if (i == '_empty_') {
obj[""] = this.emptyFix(obj['_empty_']);
delete obj['_empty_'];
} else {
obj[i] = this.emptyFix(obj[i]);
}
}
}
return obj
}
/** Function delData
* Deletes data from JSONStore
*
* Parameters:
* (Array) vars = Variables to delete from JSON store
*
* Returns:
* Status of delete attempt.
*/
this.delData = function(vars) {
if (typeof(TROPHYIM_JSON_STORE) != undefined) {
Strophe.debug("Retrieving JSONStore data");
var xhr = this._newXHR();
var deldata = "del=" + vars.join(",");
try {
xhr.open("POST", TROPHYIM_JSON_STORE, false);
} catch (e) {
Strophe.error("JSONStore open failed.");
return false;
}
xhr.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', deldata.length);
xhr.send(deldata);
if (xhr.readyState == 4 && xhr.status == 200) {
try {
var dataObj = JSON.parse(xhr.responseText);
return dataObj;
} catch(e) {
Strophe.error("Could not parse JSONStore response");
return false;
}
} else {
Strophe.error("JSONStore open failed. Status: " + xhr.status);
return false;
}
}
}
/** Function setData
* Stores data in JSONStore, overwriting values if they exist
*
* Parameters:
* (Object) vars : Object containing named vars to store ({name: value,
* othername: othervalue})
*
* Returns:
* Status of storage attempt
*/
this.setData = function(vars) {
if (typeof(TROPHYIM_JSON_STORE) != undefined) {
Strophe.debug("Storing JSONStore data");
var senddata = "set=" + JSON.stringify(vars);
var xhr = this._newXHR();
try {
xhr.open("POST", TROPHYIM_JSON_STORE, false);
} catch (e) {
Strophe.error("JSONStore open failed.");
return false;
}
xhr.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', senddata.length);
xhr.send(senddata);
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
"OK") {
return true;
} else {
Strophe.error("JSONStore open failed. Status: " + xhr.status);
return false;
}
}
}
var testData = true;
if (this.setData({testData:testData})) {
var testResult = this.getData(['testData']);
if (testResult && testResult['testData'] == true) {
this.store_working = true;
}
}
}
/** Constants: Node types
*
* Implementations of constants that IE doesn't have, but we need.
*/
if (document.ELEMENT_NODE == null) {
document.ELEMENT_NODE = 1;
document.ATTRIBUTE_NODE = 2;
document.TEXT_NODE = 3;
document.CDATA_SECTION_NODE = 4;
document.ENTITY_REFERENCE_NODE = 5;
document.ENTITY_NODE = 6;
document.PROCESSING_INSTRUCTION_NODE = 7;
document.COMMENT_NODE = 8;
document.DOCUMENT_NODE = 9;
document.DOCUMENT_TYPE_NODE = 10;
document.DOCUMENT_FRAGMENT_NODE = 11;
document.NOTATION_NODE = 12;
}
/** Function: importNode
*
* document.importNode implementation for IE, which doesn't have importNode
*
* Parameters:
* (Object) node - dom object
* (Boolean) allChildren - import node's children too
*/
if (!document.importNode) {
document.importNode = function(node, allChildren) {
switch (node.nodeType) {
case document.ELEMENT_NODE:
var newNode = document.createElement(node.nodeName);
if (node.attributes && node.attributes.length > 0) {
for(var i = 0; i < node.attributes.length; i++) {
newNode.setAttribute(node.attributes[i].nodeName,
node.getAttribute(node.attributes[i].nodeName));
}
}
if (allChildren && node.childNodes &&
node.childNodes.length > 0) {
for (var i = 0; i < node.childNodes.length; i++) {
newNode.appendChild(document.importNode(
node.childNodes[i], allChildren));
}
}
return newNode;
break;
case document.TEXT_NODE:
case document.CDATA_SECTION_NODE:
case document.COMMENT_NODE:
return document.createTextNode(node.nodeValue);
break;
}
};
}
/** Function: getElementsByClassName
*
* DOMObject.getElementsByClassName implementation for browsers that don't
* support it yet.
*
* Developed by Robert Nyman, http://www.robertnyman.com
* Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
if (document.getElementsByClassName) {
getElementsByClassName = function (className, tag, elm) {
elm = elm || document;
var elements = elm.getElementsByClassName(className),
nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
returnElements = [],
current;
for(var i=0, il=elements.length; i<il; i+=1){
current = elements[i];
if(!nodeName || nodeName.test(current.nodeName)) {
returnElements.push(current);
}
}
return returnElements;
};
} else if (document.evaluate) {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = "",
xhtmlNamespace = "http://www.w3.org/1999/xhtml",
namespaceResolver = (document.documentElement.namespaceURI ===
xhtmlNamespace)? xhtmlNamespace : null,
returnElements = [],
elements,
node;
for(var j=0, jl=classes.length; j<jl; j+=1){
classesToCheck += "[contains(concat(' ', @class, ' '), ' " +
classes[j] + " ')]";
}
try {
elements = document.evaluate(".//" + tag + classesToCheck,
elm, namespaceResolver, 0, null);
} catch (e) {
elements = document.evaluate(".//" + tag + classesToCheck,
elm, null, 0, null);
}
while ((node = elements.iterateNext())) {
returnElements.push(node);
}
return returnElements;
};
} else {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = [],
elements = (tag === "*" && elm.all)? elm.all :
elm.getElementsByTagName(tag),
current,
returnElements = [],
match;
for(var k=0, kl=classes.length; k<kl; k+=1){
classesToCheck.push(new RegExp("(^|\\s)" + classes[k] +
"(\\s|$)"));
}
for(var l=0, ll=elements.length; l<ll; l+=1){
current = elements[l];
match = false;
for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
match = classesToCheck[m].test(current.className);
if (!match) {
break;
}
}
if (match) {
returnElements.push(current);
}
}
return returnElements;
};
}
return getElementsByClassName(className, tag, elm);
};
/**
*
* Bootstrap self into window.onload and window.onunload
*/
var oldonload = window.onload;
window.onload = function() {
if(oldonload) {
oldonload();
}
TrophyIM.load();
};
var oldonunload = window.onunload;
window.onunload = function() {
if(oldonunload) {
oldonunload();
}
TrophyIM.storeData();
}
| wraithgar/trophyim | 0 | Automatically exported from code.google.com/p/trophyim | JavaScript | wraithgar | Gar | |
WSMorseGestureRecognizer/WSMorseClassifier.h | C/C++ Header | //
// WSMorseClassifier.h
// WSMorseGestureRecognizer
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef enum : NSUInteger {
/**
* The "dot", also known as a "dit" is the short signal in Morse code. It is represented by one unit of time.
*/
MorseUnitTypeDot = 1,
/**
* The "dash", also known as a "dah" is the long signal in Morse code. It is represented by three units of time.
*/
MorseUnitTypeDash = 3,
} MorseUnitType;
/**
* Convert an instance of NSNumber to a Morse unit.
*/
MorseUnitType MorseUnitTypeFromNumber(NSNumber *number);
/**
* Convert a Morse unit to a new instance of NSNumber.
*/
NSNumber *NumberFromMorseUnit(MorseUnitType morseUnit);
/**
* Convert a Morse unit to a string representation, either "." or "-".
*/
NSString *StringFromMorseUnit(MorseUnitType morseUnit);
/**
* Morse conversion and classification helpers.
*/
@interface WSMorseClassifier : NSObject
/**
* Singleton instance of the classifier
*/
+ (instancetype)sharedInstance;
/**
* Classify a touch duration interval as a Morse unit, based on the unit's unit of time.
*
* @param touchDuration The duration of the touch to classify
*
* @return classified Morse unit type
*/
- (MorseUnitType)morseUnitTypeFromTouchDuration:(NSTimeInterval)touchDuration;
/**
* Attempt to convert a sequence of Morse units to a character.
*
* @param unitSequence The sequence of Morse units in NSNumber form to convert into a character
*
* @return The string representation of the sequence if one exists, otherwise nil
*/
- (nullable NSString *)characterFromMorseUnitSequence:(NSArray<NSNumber *> *)unitSequence;
@end
NS_ASSUME_NONNULL_END
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizer/WSMorseClassifier.m | Objective-C | //
// WSMorseClassifier.m
// WSMorseGestureRecognizer
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import "WSMorseClassifier.h"
#import "WSMorseNode.h"
MorseUnitType MorseUnitTypeFromNumber(NSNumber *number) {
NSUInteger intValue = [number unsignedIntegerValue];
assert(intValue == MorseUnitTypeDot || intValue == MorseUnitTypeDash);
return intValue;
}
NSNumber *NumberFromMorseUnit(MorseUnitType morseUnit) {
return @(morseUnit);
}
NSString *StringFromMorseUnit(MorseUnitType morseUnit) {
switch (morseUnit) {
case MorseUnitTypeDot:
return @".";
case MorseUnitTypeDash:
return @"-";
}
}
/**
* Threshold at which a dot touch duration becomes a dash.
*/
static const NSTimeInterval kDashTouchDurationThreshold = ((float)MorseUnitTypeDot + (float)MorseUnitTypeDash) / 2 / 10;
@interface WSMorseClassifier ()
@property (nonatomic) WSMorseNode *rootNode;
@end
@implementation WSMorseClassifier
+ (instancetype)sharedInstance {
static WSMorseClassifier *sharedInstance = nil;
if (sharedInstance == nil) {
sharedInstance = [[WSMorseClassifier alloc] init];
}
return sharedInstance;
}
- (instancetype)init {
if (self = [super init]) {
_rootNode = [WSMorseNode morseTree];
}
return self;
}
- (MorseUnitType)morseUnitTypeFromTouchDuration:(NSTimeInterval)touchDuration {
double __unused wat = kDashTouchDurationThreshold;
return (touchDuration > kDashTouchDurationThreshold) ? MorseUnitTypeDash : MorseUnitTypeDot;
}
- (NSString *)characterFromMorseUnitSequence:(NSArray<NSNumber *> *)unitSequence {
WSMorseNode *currentNode = self.rootNode;
for (NSNumber *unitNumber in unitSequence) {
MorseUnitType unitType = MorseUnitTypeFromNumber(unitNumber);
switch (unitType) {
case MorseUnitTypeDot:
currentNode = currentNode.childDot;
break;
case MorseUnitTypeDash:
currentNode = currentNode.childDash;
break;
}
if (!currentNode) {
return nil;
}
}
return currentNode.character;
}
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizer/WSMorseGestureRecognizer.h | C/C++ Header | //
// WSMorseGestureRecognizer.h
// WSMorseGestureRecognizer
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>
//! Project version number for WSMorseGestureRecognizer.
FOUNDATION_EXPORT double WSMorseGestureRecognizerVersionNumber;
//! Project version string for WSMorseGestureRecognizer.
FOUNDATION_EXPORT const unsigned char WSMorseGestureRecognizerVersionString[];
NS_ASSUME_NONNULL_BEGIN
@class WSMorseGestureRecognizer;
@protocol WSMorseGestureRecognizerDelegate <UIGestureRecognizerDelegate>
@optional
/**
* Called when a morse tap began.
*
* @param morseGestureRecognizer The current Morse gesture recognizer
*/
- (void)morseGestureRecognizerDidBeginTap:(WSMorseGestureRecognizer *)morseGestureRecognizer;
/**
* Called when a morse tap ended.
*
* @param morseGestureRecognizer The current Morse gesture recognizer
*/
- (void)morseGestureRecognizerDidEndTap:(WSMorseGestureRecognizer *)morseGestureRecognizer;
/**
* Called when the gesture recognizer recognized a tap as a dot or dash
*
* @param morseGestureRecognizer The current Morse gesture recognizer
* @param morseUnit The string representation of the dot or dash
*/
- (void)morseGestureRecognizer:(WSMorseGestureRecognizer *)morseGestureRecognizer
didRecognizeMorseUnit:(NSString *)morseUnit;
/**
* Called when the gesture recognizer recognized a sequence of morse units as a character
*
* @param morseGestureRecognizer The current Morse gesture recognizer
* @param morseUnit The string representation of character recognized
*/
- (void)morseGestureRecognizer:(WSMorseGestureRecognizer *)morseGestureRecognizer
didRecognizeCharacter:(NSString *)character;
/**
* Called when the gesture recognizer recognized a sequence of characters as a word
*
* @param morseGestureRecognizer The current Morse gesture recognizer
* @param morseUnit The string representation of the last word recognized
*/
- (void)morseGestureRecognizer:(WSMorseGestureRecognizer *)morseGestureRecognizer
didRecognizeWord:(NSString *)word;
@end
/**
* UIGestureRecognizer subclass for recognizing and detecting Morse Code.
*/
@interface WSMorseGestureRecognizer : UIGestureRecognizer
@property (nonatomic, weak) id<WSMorseGestureRecognizerDelegate> delegate;
/**
* String of alphanumeric characters to recognize in Morse Code.
*/
@property (nonatomic, copy) NSString *stringToRecognize;
/**
* Delay after touch up before which the tapped Morse sequence is converted into a character. Reset on touch down.
* Defaults to 0.3 seconds.
*/
@property (nonatomic) NSTimeInterval characterParseDelay;
/**
* Delay after character parse before which the character sequence is converted into a word. Reset on touch down.
* Defaults to 1.5 seconds.
*/
@property (nonatomic) NSTimeInterval wordParseDelay;
@end
NS_ASSUME_NONNULL_END
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizer/WSMorseGestureRecognizer.m | Objective-C | //
// WSMorseGestureRecognizer.m
// WSMorseGestureRecognizer
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import "WSMorseGestureRecognizer.h"
#import "WSMorseClassifier.h"
/**
* Default time intervals for parse delays
*/
static const NSTimeInterval kDefaultCharacterParseDelayInterval = 0.3;
static const NSTimeInterval kDefaultWordParseDelayInterval = 1.5;
@interface WSMorseGestureRecognizer ()
/**
* Full parsed character history for this instance, with words separated by spaces.
*/
@property (nonatomic) NSString *letterHistory;
/**
* The current sequence of morse units (stored as NSNumbers) that will be converted to a character
* after the character parse delay.
*/
@property (nonatomic) NSMutableArray<NSNumber *> *currentSequence;
/**
* Timestamp of the start of the last touch. Used to determine dot vs dash.
*/
@property (nonatomic) NSTimeInterval timeOfLastTouchStart;
@end
@implementation WSMorseGestureRecognizer
- (instancetype)initWithTarget:(id)target action:(SEL)action {
if (self = [super initWithTarget:target action:action]) {
_letterHistory = @"";
_currentSequence = [NSMutableArray array];
_characterParseDelay = kDefaultCharacterParseDelayInterval;
_wordParseDelay = kDefaultWordParseDelayInterval;
}
return self;
}
#pragma mark - UIGestureRecognizerSubclass
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if ([self.delegate respondsToSelector:@selector(morseGestureRecognizerDidBeginTap:)]) {
[self.delegate morseGestureRecognizerDidBeginTap:self];
}
if (self.state == UIGestureRecognizerStatePossible) {
self.state = UIGestureRecognizerStateBegan;
}
[self cancelTimerRequests];
self.timeOfLastTouchStart = [[NSDate date] timeIntervalSince1970];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if ([self.delegate respondsToSelector:@selector(morseGestureRecognizerDidEndTap:)]) {
[self.delegate morseGestureRecognizerDidEndTap:self];
}
NSTimeInterval timeOfTouchEnd = [[NSDate date] timeIntervalSince1970];
NSTimeInterval durationOfTouch = timeOfTouchEnd - self.timeOfLastTouchStart;
MorseUnitType unitType = [[WSMorseClassifier sharedInstance] morseUnitTypeFromTouchDuration:durationOfTouch];
[self.currentSequence addObject:NumberFromMorseUnit(unitType)];
if ([self.delegate respondsToSelector:@selector(morseGestureRecognizer:didRecognizeMorseUnit:)]) {
[self.delegate morseGestureRecognizer:self didRecognizeMorseUnit:StringFromMorseUnit(unitType)];
}
[self performSelector:@selector(endRecognizerForCurrentCharacter) withObject:nil afterDelay:self.characterParseDelay];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.state = UIGestureRecognizerStateCancelled;
[self cancelTimerRequests];
}
#pragma mark - Timed Method Calls
- (void)cancelTimerRequests {
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(endRecognizerForCurrentCharacter)
object:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(endRecognizerForCurrentWord)
object:nil];
}
- (void)endRecognizerForCurrentCharacter {
self.state = UIGestureRecognizerStateChanged;
NSString *possibleCurrentCharacter = [[WSMorseClassifier sharedInstance] characterFromMorseUnitSequence:self.currentSequence];
if (possibleCurrentCharacter) {
self.letterHistory = [self.letterHistory stringByAppendingString:possibleCurrentCharacter];
if ([self.delegate respondsToSelector:@selector(morseGestureRecognizer:didRecognizeCharacter:)]) {
[self.delegate morseGestureRecognizer:self didRecognizeCharacter:possibleCurrentCharacter];
}
}
[self.currentSequence removeAllObjects];
[self performSelector:@selector(endRecognizerForCurrentWord)
withObject:nil
afterDelay:self.wordParseDelay];
}
- (void)endRecognizerForCurrentWord {
self.state = UIGestureRecognizerStateChanged;
NSRange wordMatch = [self.letterHistory rangeOfString:@" " options:(NSCaseInsensitiveSearch | NSBackwardsSearch)];
NSString *word = wordMatch.location != NSNotFound ? [self.letterHistory substringFromIndex:wordMatch.location + 1] : self.letterHistory;
if (self.stringToRecognize) {
NSRange match = [self.letterHistory rangeOfString:self.stringToRecognize
options:(NSCaseInsensitiveSearch | NSBackwardsSearch)];
if (match.location == self.letterHistory.length - self.stringToRecognize.length &&
word.length == self.stringToRecognize.length) {
self.state = UIGestureRecognizerStateRecognized;
}
}
if ([self.delegate respondsToSelector:@selector(morseGestureRecognizer:didRecognizeWord:)]) {
[self.delegate morseGestureRecognizer:self didRecognizeWord:word];
}
self.letterHistory = [self.letterHistory stringByAppendingString:@" "];
}
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizer/WSMorseNode.h | C/C++ Header | //
// WSMorseNode.h
// WSMorseGestureRecognizer
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Node in a binary search tree that stores the conversion from Morse into alphanumeric characters.
*/
@interface WSMorseNode : NSObject
/**
* Tree of WSMorseNode. To parse, start at root returned by this function and follow dot or dash edges in order
* specified by Morse sequence being parsed. At end of sequence, the character property represents the sequence.
*/
+ (WSMorseNode *)morseTree;
/**
* Character for morse sequence terminating at this node.
*/
@property (nonatomic, copy) NSString *character;
/**
* Node when next Morse unit in the sequence is a dot.
*/
@property (nonatomic) WSMorseNode *childDot;
/**
* Node when next Morse unit in the sequence is a dash.
*/
@property (nonatomic) WSMorseNode *childDash;
@end
NS_ASSUME_NONNULL_END
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizer/WSMorseNode.m | Objective-C | //
// WSMorseNode.m
// WSMorseGestureRecognizer
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import "WSMorseNode.h"
@implementation WSMorseNode
+ (WSMorseNode *)morseTree {
WSMorseNode *rootNode = [[WSMorseNode alloc] init];
[[WSMorseNode translationDictionary]
enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
[WSMorseNode addStringToTree:rootNode stringToAdd:key character:obj];
}];
return rootNode;
}
+ (WSMorseNode *)addStringToTree:(WSMorseNode *)currentNode
stringToAdd:(NSString *)stringToAdd
character:(NSString *)character {
if ([stringToAdd isEqualToString:@""]) {
NSAssert(!currentNode.character, @"Attempting to set duplicate character: %@ (%@ exists here)",
character,
currentNode.character);
currentNode.character = character;
return currentNode;
}
unichar firstMorseCharacter = [stringToAdd characterAtIndex:0];
WSMorseNode *childNode;
if (firstMorseCharacter == '.') {
if (!currentNode.childDot) {
childNode = [[WSMorseNode alloc] init];
currentNode.childDot = childNode;
}
childNode = currentNode.childDot;
} else if (firstMorseCharacter == '-') {
if (!currentNode.childDash) {
childNode = [[WSMorseNode alloc] init];
currentNode.childDash = childNode;
}
childNode = currentNode.childDash;
} else {
NSAssert(NO, @"Invalid morse character: %hu", firstMorseCharacter);
}
NSString *nextString = stringToAdd.length > 1 ? [stringToAdd substringFromIndex:1] : @"";
return [WSMorseNode addStringToTree:childNode stringToAdd:nextString character:character];
}
+ (NSDictionary<NSString *, NSString *> *)translationDictionary {
return @{
@".-" : @"A",
@"-..." : @"B",
@"-.-." : @"C",
@"-.." : @"D",
@"." : @"E",
@"..-." : @"F",
@"--." : @"G",
@"...." : @"H",
@".." : @"I",
@".---" : @"J",
@"-.-" : @"K",
@".-.." : @"L",
@"--" : @"M",
@"-." : @"N",
@"---" : @"O",
@".--." : @"P",
@"--.-" : @"Q",
@".-." : @"R",
@"..." : @"S",
@"-" : @"T",
@"..-" : @"U",
@"...-" : @"V",
@".--" : @"W",
@"-..-" : @"X",
@"-.--" : @"Y",
@"--.." : @"Z",
@"-----" : @"0",
@".----" : @"1",
@"..---" : @"2",
@"...--" : @"3",
@"....-" : @"4",
@"....." : @"5",
@"-...." : @"6",
@"--..." : @"7",
@"---.." : @"8",
@"----." : @"9",
@".-.-.-" : @".",
@"--..--" : @",",
@"..--.." : @"?",
@".----." : @"'",
@"-.-.--" : @"!",
@"-..-." : @"/",
@"-.--." : @"(",
@"-.--.-" : @")",
@".-..." : @"&",
@"---..." : @":",
@"-.-.-." : @";",
@"-...-" : @"=",
@".-.-." : @"+",
@"-....-" : @"-",
@"..--.-" : @"_",
@".-..-." : @"\"",
@"...-..-" : @"$",
@".--.-." : @"@",
@".-.-" : @"\n",
@"...-." : @"*",
};
}
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizerDemo/WSMorseGestureRecognizerDemo/AppDelegate.h | C/C++ Header | //
// AppDelegate.h
// WSMorseGestureRecognizerDemo
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizerDemo/WSMorseGestureRecognizerDemo/AppDelegate.m | Objective-C | //
// AppDelegate.m
// WSMorseGestureRecognizerDemo
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.window setRootViewController:[[UINavigationController alloc] initWithRootViewController:[ViewController new]]];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizerDemo/WSMorseGestureRecognizerDemo/ViewController.h | C/C++ Header | //
// ViewController.h
// WSMorseGestureRecognizerDemo
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizerDemo/WSMorseGestureRecognizerDemo/ViewController.m | Objective-C | //
// ViewController.m
// WSMorseGestureRecognizerDemo
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import "ViewController.h"
@import WSMorseGestureRecognizer;
typedef enum : NSUInteger {
LabelTypeUnit,
LabelTypeCharacter,
LabelTypeWord,
} LabelType;
@interface ViewController () <WSMorseGestureRecognizerDelegate>
@property (nonatomic) UIImageView *image;
@property (nonatomic) UILabel *eventLabel;
@property (nonatomic) LabelType lastLabelType;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"WSMorseGestureRecognizer Demo";
self.view.backgroundColor = [UIColor whiteColor];
self.eventLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.eventLabel.textColor = [UIColor blackColor];
self.eventLabel.font = [UIFont systemFontOfSize:70 weight:UIFontWeightBlack];
self.eventLabel.textAlignment = NSTextAlignmentCenter;
self.eventLabel.text = @"";
[self.view addSubview:self.eventLabel];
self.image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"morse_up"]
highlightedImage:[UIImage imageNamed:@"morse_down"]];
[self.view addSubview:self.image];
WSMorseGestureRecognizer *gestureRecognizer = [[WSMorseGestureRecognizer alloc] initWithTarget:self
action:@selector(morseAction:)];
gestureRecognizer.stringToRecognize = @"SOS";
gestureRecognizer.delegate = self;
[self.view addGestureRecognizer:gestureRecognizer];
}
- (void)viewDidLayoutSubviews {
self.eventLabel.frame = CGRectMake(0, 0, self.view.bounds.size.width, 70);
self.eventLabel.center = CGPointMake(self.view.center.x, self.view.bounds.size.height * .3);
self.image.center = CGPointMake(self.view.center.x, self.view.bounds.size.height * .8);
}
- (void)morseAction:(WSMorseGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateRecognized) {
[UIView animateWithDuration:0.1 animations:^{
self.view.backgroundColor = [UIColor greenColor];
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.7 animations:^{
self.view.backgroundColor = [UIColor whiteColor];
}];
}];
}
}
#pragma mark - WSMorseGestureRecognizerDelegate
- (void)morseGestureRecognizer:(WSMorseGestureRecognizer *)morseGestureRecognizer
didRecognizeMorseUnit:(NSString *)morseUnit {
[self showLabel:morseUnit labelType:LabelTypeUnit];
}
- (void)morseGestureRecognizer:(WSMorseGestureRecognizer *)morseGestureRecognizer
didRecognizeCharacter:(NSString *)character {
[self showLabel:character labelType:LabelTypeCharacter];
}
- (void)morseGestureRecognizer:(WSMorseGestureRecognizer *)morseGestureRecognizer
didRecognizeWord:(NSString *)word {
[self showLabel:word labelType:LabelTypeWord];
}
- (void)morseGestureRecognizerDidBeginTap:(WSMorseGestureRecognizer *)morseGestureRecognizer {
[self.image setHighlighted:YES];
}
- (void)morseGestureRecognizerDidEndTap:(WSMorseGestureRecognizer *)morseGestureRecognizer {
[self.image setHighlighted:NO];
}
#pragma mark - Private
- (void)showLabel:(NSString *)string labelType:(LabelType)labelType {
NSString *afterLabel = string;
if (labelType == LabelTypeUnit && self.lastLabelType == LabelTypeUnit) {
afterLabel = [self.eventLabel.text stringByAppendingString:string];
}
self.lastLabelType = labelType;
[UIView animateWithDuration:0 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
self.eventLabel.text = afterLabel;
self.eventLabel.alpha = 1.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.7 delay:2.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
self.eventLabel.alpha = 0.0;
} completion:^(BOOL finished) {
}];
}];
}
@end
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
WSMorseGestureRecognizerDemo/WSMorseGestureRecognizerDemo/main.m | Objective-C | //
// main.m
// WSMorseGestureRecognizerDemo
//
// Created by William Schurman on 10/29/15.
// Copyright © 2015 wschurman. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| wschurman/WSMorseGestureRecognizer | 23 | iOS UIGestureRecognizer that recognizes and parses Morse code tap events. | Objective-C | wschurman | Will Schurman 🦦 | expo |
src/OpenArk/about/about.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "about.h"
#include "../common/common.h"
About::About(QWidget* parent)
{
ui.setupUi(this);
connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); });
setAttribute(Qt::WA_ShowModal, true);
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(windowFlags()& ~(Qt::WindowMaximizeButtonHint| Qt::WindowMinimizeButtonHint)| Qt::MSWindowsFixedSizeDialogHint);
connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(close()));
}
About::~About()
{
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/about/about.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <QtCore>
#include <QtWidgets>
#include <Windows.h>
#include "ui_about.h"
namespace Ui {
class About;
}
class About : public QWidget {
Q_OBJECT
public:
About(QWidget* parent);
~About();
private slots:
private:
Ui::About ui;
}; | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/bundler-shell/main.cpp | C++ | #ifndef _CRT_RAND_S
#define _CRT_RAND_S
#endif
#include <windows.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <unone.h>
#include <thread>
#include <string>
#include <vector>
#include "../pack/pack.h"
typedef std::tuple<std::wstring, std::wstring> DirectiveSeq;
#include <stdlib.h>
bool ParseCmdline(const std::wstring& cmdline, std::vector<std::wstring>& vec)
{
try {
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(cmdline.c_str(), &argc);
for (int Index = 0; Index < argc; ++Index) {
vec.push_back(argv[Index]);
}
HeapFree(GetProcessHeap(), 0, argv);
return !vec.empty();
}
catch (...) {
vec.clear();
return false;
}
}
std::string TmRandHexString(int count)
{
char str_temp[2] = { 0 };
std::string str;
int i, x;
unsigned int randnum = 0;
const char charset[] = "0123456789ABCDEF";
if (count <= 0)
return "";
for (i = 0; i < count; ++i)
{
rand_s(&randnum);
x = randnum % (unsigned)(sizeof(charset) - 1);
sprintf_s(str_temp, "%c", charset[x]);
str.append(str_temp);
}
return str;
}
void BundleExecStart(std::wstring param, std::wstring root)
{
UNONE::StrReplaceIW(param, L"%root%", root);
UNONE::PsCreateProcessW(param);
}
void BundleExecCall(std::wstring param, std::wstring root, int show = SW_SHOW, bool wait = true)
{
UNONE::StrReplaceIW(param, L"%root%", root);
std::vector<std::wstring> vec;
ParseCmdline(param, vec);
if (vec.empty()) return;
param.clear();
for (auto i = 1; i < vec.size(); i++) {
param.append(vec[i]);
param.append(L" ");
}
SHELLEXECUTEINFOW sh = { 0 };
sh.cbSize = sizeof(SHELLEXECUTEINFOW);
sh.fMask = SEE_MASK_NOCLOSEPROCESS;
sh.hwnd = NULL;
sh.lpVerb = NULL;
sh.lpFile = vec[0].c_str();
sh.lpParameters = param.c_str();
sh.lpDirectory = NULL;
sh.nShow = show;
sh.hInstApp = NULL;
ShellExecuteExW(&sh);
if (wait) WaitForSingleObject(sh.hProcess, INFINITE);
CloseHandle(sh.hProcess);
}
void BundleExecCmd(std::wstring param, std::wstring root)
{
UNONE::StrReplaceIW(param, L"%root%", root);
BundleExecCall(L"cmd.exe /c " + param, root, false);
}
void BundleExecClean(std::wstring param, std::wstring root)
{
UNONE::FsDeleteDirectoryW(root);
}
void BundleOutputError(std::wstring msg)
{
MessageBoxW(NULL, msg.c_str(), L"error", MB_ICONERROR);
}
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
bool found = false;
LPVOID bdata = NULL;
HRSRC res = FindResourceW(GetModuleHandleW(NULL), MAKEINTRESOURCE(IDX_BUDE), IDS_BUDE);
if (res) {
HGLOBAL hg = LoadResource(GetModuleHandleW(NULL), res);
if (hg) {
bdata = LockResource(hg);
if (bdata) {
DWORD size = SizeofResource(GetModuleHandleW(NULL), res);
found = true;
}
}
}
std::string test;
if (!found) {
#ifndef _DEBUG
BundleOutputError(L"Resource is corrupted.");
return 1;
#endif
#ifdef _DEBUG
UNONE::FsReadFileDataA("c:/test.bd", test);
if (test.empty())
return 1;
#endif
bdata = (LPVOID)test.c_str();
}
std::wstring dirname;
BundleError err;
err = BundleGetDirName((const char*)bdata, dirname);
if (err != BERR_OK) {
BundleOutputError(L"Directory name invalid.");
return 1;
}
std::wstring parentdir, outdir, script;
parentdir = UNONE::OsEnvironmentW(L"%temp%\\BUDE\\") + UNONE::StrToW(TmRandHexString(12));
outdir = parentdir + L"\\" + dirname;
UNONE::FsCreateDirW(outdir);
err = BundleUnpack(outdir, (const char*)bdata, script, dirname);
if (err != BERR_OK) {
BundleOutputError(L"Unpack files error.");
return 1;
}
std::vector<std::wstring> lines;
UNONE::StrSplitLinesW(script, lines);
std::vector<DirectiveSeq> directives;
for (auto& line : lines) {
if (line.find(';') != 0) {
size_t pos = line.find(' ');
std::wstring cmd, param;
if (pos != std::wstring::npos) {
cmd = line.substr(0, pos);
param = line.substr(pos + 1);
} else {
cmd = line;
}
directives.push_back(std::make_tuple(cmd, param));
}
}
std::vector<std::thread> async_tasks;
for (auto &d : directives) {
std::wstring cmd, param;
std::tie(cmd, param) = d;
if (UNONE::StrCompareIW(cmd, L"start")) {
async_tasks.push_back(std::thread(BundleExecCall, param, outdir, SW_SHOW, true));
} else if (UNONE::StrCompareIW(cmd, L"call")) {
BundleExecCall(param, outdir);
} else if (UNONE::StrCompareIW(cmd, L"cmd")) {
BundleExecCmd(param, outdir);
} else if (UNONE::StrCompareIW(cmd, L"clean")) {
BundleExecClean(param, parentdir);
}
}
for (auto &t : async_tasks) {
t.join();
}
return 0;
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/bundler.cpp | C++ | #include "bundler.h"
#include "../common/common.h"
#include "../openark/openark.h"
#include "pack/pack.h"
#include "icons/icons.h"
#include <QFile>
Bundler::Bundler(QWidget *parent) :
parent_((OpenArk*)parent)
{
ui.setupUi(this);
connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); });
ui.folderLabel->installEventFilter(this);
ui.folderLabel->setCursor(Qt::PointingHandCursor);
setAcceptDrops(true);
QTableView *filesView = ui.filesView;
files_model_ = new QStandardItemModel;
SetDefaultTableViewStyle(filesView, files_model_);
filesView->viewport()->installEventFilter(this);
files_model_->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Size(KB)") << tr("Path"));
files_menu_ = new QMenu();
files_menu_->addAction(tr("Use the ICON"), this, SLOT(onUseIcon()));
connect(ui.openBtn, SIGNAL(clicked()), this, SLOT(onOpenFolder()));
connect(ui.selectIconBtn, SIGNAL(clicked()), this, SLOT(onSelectIcon()));
connect(ui.saveBtn, SIGNAL(clicked()), this, SLOT(onSaveTo()));
}
Bundler::~Bundler()
{
}
bool Bundler::eventFilter(QObject *obj, QEvent *e)
{
if (obj == ui.folderLabel) {
if (e->type() == QEvent::MouseButtonPress) {
ShellExecuteW(NULL, L"open", files_folder_.toStdWString().c_str(), NULL, NULL, SW_SHOW);
}
} else if (obj == ui.filesView->viewport()) {
if (e->type() == QEvent::ContextMenu) {
QContextMenuEvent* ctxevt = dynamic_cast<QContextMenuEvent*>(e);
if (ctxevt != nullptr) {
files_menu_->move(ctxevt->globalPos());
files_menu_->show();
}
}
}
return QWidget::eventFilter(obj, e);
}
void Bundler::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("text/uri-list"))
event->acceptProposedAction();
}
void Bundler::dropEvent(QDropEvent *event)
{
if (!event->mimeData()->hasUrls())
return;
QString& path = event->mimeData()->urls()[0].toLocalFile();
if (!UNONE::FsIsDirW(path.toStdWString()))
return;
OpenFolderImpl(path);
}
void Bundler::onRefresh()
{
OpenFolderImpl(files_folder_);
}
void Bundler::onOpenFolder()
{
QString folder = QFileDialog::getExistingDirectory(this, tr("Open Folder"), "");
if (folder.isEmpty()) return;
OpenFolderImpl(folder);
}
void Bundler::onSelectIcon()
{
QString file = QFileDialog::getOpenFileName(this, tr("Select ICON"), "", tr("ico/exe (*.exe;*.ico)"));
if (file.isEmpty()) return;
SelectIconImpl(file);
}
void Bundler::onUseIcon()
{
auto idx = ui.filesView->currentIndex();
auto name = GetItemModelData(files_model_, idx.row(), 2);
auto path = files_folder_ + "/" + name.replace("./", "");
SelectIconImpl(path);
}
void Bundler::onSaveTo()
{
QString bundle = QFileDialog::getSaveFileName(this,tr("Save to"),"",tr("BundleFile(*.exe)"));
if (bundle.isEmpty()) return;
std::vector<std::wstring> files;
std::vector<std::wstring> names;
for (int i = 0; i < files_model_->rowCount(); i++) {
QString name = GetItemModelData(files_model_, i, 2);
name.replace("./", "");
names.push_back(name.toStdWString());
QString path = files_folder_ + "/" + name;
files.push_back(path.toStdWString());
}
std::wstring script = ui.scriptEdit->toPlainText().toStdWString();
std::string bdata;
BundleError err = BundlePack(UNONE::FsPathToNameW(files_folder_.toStdWString()), files, names, script, bdata);
if (err != BERR_OK) {
qDebug() << tr("Build err") << err;
MsgBoxError(tr("Build bundle file err"));
return;
}
QFile f(":/OpenArk/BundlerShell.exe");
f.open(QIODevice::ReadOnly);
auto&& shell = f.readAll().toStdString();
UNONE::FsWriteFileDataW(bundle.toStdWString(), shell);
std::string icondata;
if (GetIconData(icon_file_.toStdWString(), icondata) && !icondata.empty()) {
SetIconData(bundle.toStdWString(), icondata);
}
HANDLE upt = BeginUpdateResourceW(bundle.toStdWString().c_str(), FALSE);
if (!upt) {
qDebug() << tr("BeginUpdateResourceW err") << GetLastError();
MsgBoxError(tr("BeginUpdateResourceW err"));
return;
}
if (!UpdateResourceW(upt, IDS_BUDE, MAKEINTRESOURCEW(IDX_BUDE), MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
(LPVOID)bdata.data(), bdata.size())) {
qDebug() << tr("UpdateResourceW err") << GetLastError();
MsgBoxError(tr("UpdateResourceW err"));
return;
}
EndUpdateResource(upt, FALSE);
MsgBoxInfo(QString(tr("Build %1 ok").arg(bundle)));
UNONE::FsWriteFileDataA("c:/xxx.bd", bdata);
/*
std::string d1;
std::wstring sc;
std::wstring outdir = L"i:/5566";
BundleUnpack(outdir, bdata.c_str(), sc);
*/
}
void Bundler::OpenFolderImpl(QString folder)
{
if (folder.isEmpty()) return;
//folder.replace("/", "\\");
files_folder_ = folder;
ui.folderLabel->setText(folder);
ClearItemModelData(files_model_);
UNONE::DirEnumCallbackW fcb = [&](wchar_t* path, wchar_t* name, void* param)->bool {
if (UNONE::FsIsDirW(path)) {
UNONE::FsEnumDirectoryW(path, fcb, param);;
return true;
}
InitTableItem(files_model_);
AppendTableIconItem(files_model_, LoadIcon(WCharsToQ(path)), WCharsToQ(name));
DWORD64 size;
UNONE::FsGetFileSizeW(path, size);
AppendTableItem(files_model_, WStrToQ(UNONE::StrFormatW(L"%.2f", ((double)size) / 1024)));
std::wstring p(path);
UNONE::StrReplaceW(p, folder.toStdWString(), L".");
UNONE::StrReplaceW(p, L"\\", L"/");
AppendTableItem(files_model_, WStrToQ(p));
return true;
};
UNONE::FsEnumDirectoryW(folder.toStdWString(), fcb);
}
void Bundler::SelectIconImpl(QString icon)
{
icon_file_ = icon;
ui.iconLabel->setPixmap(LoadIcon(icon).pixmap(24, 24));
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/bundler.h | C/C++ Header | #pragma once
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
#include <QMutex>
#include <Windows.h>
#include <mutex>
#include "ui_bundler.h"
namespace Ui {
class Bundler;
class OpenArkWindow;
}
class OpenArk;
class Bundler : public QWidget {
Q_OBJECT
public:
Bundler(QWidget *parent);
~Bundler();
protected:
bool eventFilter(QObject *obj, QEvent *e);
private slots:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
void onRefresh();
void onOpenFolder();
void onSelectIcon();
void onUseIcon();
void onSaveTo();
private:
void OpenFolderImpl(QString folder);
void SelectIconImpl(QString icon);
private:
Ui::Bundler ui;
OpenArk *parent_;
QString files_folder_;
QString icon_file_;
QMenu *files_menu_;
QStandardItemModel *files_model_;
}; | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/crc32/crc32.cpp | C++ | #include "crc32.h"
static uint32_t crc32_tab[] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
uint32_t crc32(const void *buf, size_t size, uint32_t init_crc)
{
const uint8_t *p;
p = (uint8_t *)buf;
init_crc = init_crc ^ ~0U;
while (size--)
init_crc = crc32_tab[(init_crc ^ *p++) & 0xFF] ^ (init_crc >> 8);
return init_crc ^ ~0U;
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/crc32/crc32.h | C/C++ Header | #pragma once
#include <stdint.h>
uint32_t crc32(const void *buf, size_t size, uint32_t init_crc = 0); | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/icons/icons.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "icons.h"
#include <unone.h>
using namespace std;
//#define FIELD_OFFSET(type, field) ((ULONG)&(((type *)0)->field))
typedef struct
{
BYTE bWidth; // Width, in pixels, of the image
BYTE bHeight; // Height, in pixels, of the image
BYTE bColorCount; // Number of colors in image (0 if >=8bpp)
BYTE bReserved; // Reserved ( must be 0)
WORD wPlanes; // Color Planes
WORD wBitCount; // Bits per pixel
DWORD dwBytesInRes; // How many bytes in this resource?
DWORD dwImageOffset; // Where in the file is this image?
} ICONDIRENTRY, *LPICONDIRENTRY;
typedef struct
{
WORD idReserved; // Reserved (must be 0)
WORD idType; // Resource Type (1 for icons)
WORD idCount; // How many images?
//ICONDIRENTRY idEntries[1]; // An entry for each image (idCount of 'em)
} ICONDIR, *LPICONDIR;
#pragma pack( push )
#pragma pack( 2 )
typedef struct
{
BYTE bWidth; // Width, in pixels, of the image
BYTE bHeight; // Height, in pixels, of the image
BYTE bColorCount; // Number of colors in image (0 if >=8bpp)
BYTE bReserved; // Reserved
WORD wPlanes; // Color Planes
WORD wBitCount; // Bits per pixel
DWORD dwBytesInRes; // how many bytes in this resource?
WORD nID; // the ID
} GRPICONDIRENTRY, *LPGRPICONDIRENTRY;
#pragma pack( pop )
// #pragmas are used here to insure that the structure's
// packing in memory matches the packing of the EXE or DLL.
#pragma pack( push )
#pragma pack( 2 )
typedef struct
{
WORD idReserved; // Reserved (must be 0)
WORD idType; // Resource type (1 for icons)
WORD idCount; // How many images?
GRPICONDIRENTRY idEntries[1]; // The entries for each image
} GRPICONDIR, *LPGRPICONDIR;
#pragma pack( pop )
typedef struct
{
LPCSTR ResType;
LPCSTR ResName;
DWORD ResSize;
WORD ResLanguage;
} RESINFO, *PRESINFO;
BOOL CALLBACK EnumFirstResProc(HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG_PTR lParam)
{
if (IS_INTRESOURCE(lpszName))
sprintf_s((CHAR*)lParam, MAX_PATH, "#%d", (USHORT)lpszName);
else
strncpy_s((CHAR*)lParam, MAX_PATH, lpszName, MAX_PATH - 1);
return FALSE;
}
BOOL CALLBACK EnumLastResIdProc(HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG_PTR lParam)
{
if (IS_INTRESOURCE(lpszName))
sprintf_s((CHAR*)lParam, MAX_PATH, "#%d", (USHORT)lpszName);
return TRUE;
}
BOOL CALLBACK EnumFirstResLangProc(HMODULE hModule, LPCSTR lpszType, LPCSTR lpszName, WORD wIDLanguage, LONG_PTR lParam)
{
*(WORD*)lParam = wIDLanguage;
return FALSE;
}
bool GetResLanguage(HMODULE Module, LPCSTR ResType, LPCSTR ResName, WORD& Language)
{
return EnumResourceLanguagesA(Module, (LPCSTR)RT_GROUP_ICON, ResName, EnumFirstResLangProc, (LONG_PTR)&Language) ? true : false;
}
bool GetResData(HMODULE Module, LPCSTR ResType, LPCSTR ResName, LPVOID& Data, DWORD& Size)
{
HRSRC Res = FindResourceA(Module, ResName, ResType);
if (!Res)
return false;
HGLOBAL Global = LoadResource(Module, Res);
if (!Global)
return false;
Size = SizeofResource(Module, Res);
Data = LockResource(Global);
if (!Data)
return false;
return true;
}
bool SetResData(HANDLE Update, LPCSTR ResType, LPCSTR ResName, LPVOID& Data, DWORD& Size, WORD wLanguage = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT))
{
return UpdateResourceA(Update, ResType, ResName, wLanguage, Data, Size) ? true : false;
}
bool DeleteResData(HANDLE Update, LPCSTR ResType, LPCSTR ResName, WORD ResLanguage)
{
return UpdateResourceA(Update, ResType, ResName, ResLanguage, NULL, 0) ? true : false;
return true;
}
bool GetIconData(const std::wstring& ExePath, std::string& IconData)
{
bool Result = false;
HMODULE Module = NULL;
LPICONDIRENTRY IconEntry = NULL;
if (ExePath.empty())
return false;
int pos = ExePath.find_last_of(L".");
if (pos != std::wstring::npos && ExePath.substr(pos) == L".ico") {
return UNONE::FsReadFileDataW(ExePath, IconData);
}
do {
Module = LoadLibraryExW(ExePath.c_str(), NULL, LOAD_LIBRARY_AS_DATAFILE);
if (!Module)
break;
CHAR ResGroupName[MAX_PATH] = { 0 };
if (!EnumResourceNamesA(Module, (LPCSTR)RT_GROUP_ICON, EnumFirstResProc, (LONG_PTR)ResGroupName) &&
GetLastError() == ERROR_RESOURCE_TYPE_NOT_FOUND)
break;
LPCSTR ResName = NULL;
if (ResGroupName[0] == '#')
ResName = MAKEINTRESOURCEA(atoi(&ResGroupName[1]));
else
ResName = ResGroupName;
LPGRPICONDIR ResGroupData = NULL;
DWORD ResGroupSize = 0;
if (!GetResData(Module, (LPCSTR)RT_GROUP_ICON, ResName, (LPVOID&)ResGroupData, ResGroupSize))
break;
DWORD Count = ResGroupData->idCount;
ICONDIR IconDir;
memcpy(&IconDir, ResGroupData, sizeof(ICONDIR));
DWORD Offset = 0, Size = 0;
IconEntry = new(std::nothrow) ICONDIRENTRY[Count];
if (!IconEntry)
break;
Offset += sizeof(ICONDIR) + sizeof(ICONDIRENTRY)*Count;
for (DWORD i = 0; i < Count; i++)
{
memcpy(&IconEntry[i], &ResGroupData->idEntries[i], sizeof(GRPICONDIRENTRY));
LPVOID IconItem = NULL;
DWORD IconItemSize = 0;
GetResData(Module, (LPCSTR)RT_ICON, MAKEINTRESOURCEA(ResGroupData->idEntries[i].nID), IconItem, IconItemSize);
Size = Offset + IconItemSize;
IconData.resize(Size);
memcpy(&IconData[Offset], IconItem, IconItemSize);
IconEntry[i].dwImageOffset = Offset;
IconEntry[i].dwBytesInRes = IconItemSize;
Offset += IconItemSize;
UnlockResource(IconItem);
}
UnlockResource(ResGroupData);
memcpy(&IconData[0], &IconDir, sizeof(ICONDIR));
memcpy(&IconData[sizeof(ICONDIR)], IconEntry, sizeof(ICONDIRENTRY)*Count);
Result = true;
} while (0);
if (Module)
FreeLibrary(Module);
if (IconEntry)
delete[] IconEntry;
return Result;
}
bool SetIconData(const std::wstring& ExePath, std::string& IconData)
{
bool Result = false;
HMODULE Module = NULL;
LPICONDIRENTRY IconEntry = NULL;
if (ExePath.empty())
return false;
LPGRPICONDIR ResGroupData = NULL;
BOOL IsGroupExsited = FALSE;
LPCSTR GroupName = NULL;
WORD OriResLang = 0;
Module = LoadLibraryExW(ExePath.c_str(), NULL, LOAD_LIBRARY_AS_DATAFILE);
if (!Module)
return false;
do
{
CHAR Name[MAX_PATH] = { 0 };
if (!EnumResourceNamesA(Module, (LPCSTR)RT_GROUP_ICON, EnumFirstResProc, (LONG_PTR)Name))
break;
if (Name[0] == '#')
GroupName = MAKEINTRESOURCEA(atoi(&Name[1]));
else
GroupName = Name;
DWORD ResGroupSize = 0;
GetResData(Module, (LPCSTR)RT_GROUP_ICON, GroupName, (LPVOID&)ResGroupData, ResGroupSize);
GetResLanguage(Module, (LPCSTR)RT_GROUP_ICON, GroupName, OriResLang);
IsGroupExsited = TRUE;
} while (0);
GRPICONDIR TempGroupData;
if (!IsGroupExsited)
{
ResGroupData = &TempGroupData;
ResGroupData->idCount = 0;
GroupName = MAKEINTRESOURCEA(1);
}
vector<DWORD> AddResId;
vector<RESINFO> DelResInfo;
LPICONDIR IconDir = (LPICONDIR)&IconData[0];
LPICONDIRENTRY IconDirEntry = (LPICONDIRENTRY)&IconData[sizeof(ICONDIR)];
for (DWORD i = 0; i < ResGroupData->idCount; i++)
{
RESINFO Info =
{
(LPCSTR)RT_ICON,
MAKEINTRESOURCEA(ResGroupData->idEntries[i].nID),
ResGroupData->idEntries[i].dwBytesInRes,
OriResLang
};
DelResInfo.push_back(Info);
}
if (IconDir->idCount == ResGroupData->idCount)
{
for (DWORD i = 0; i < ResGroupData->idCount; i++)
AddResId.push_back((DWORD)ResGroupData->idEntries[i].nID);
}
else if (IconDir->idCount < ResGroupData->idCount)
{
for (DWORD i = 0; i < ResGroupData->idCount; i++)
{
if (i < IconDir->idCount)
AddResId.push_back((DWORD)ResGroupData->idEntries[i].nID);
}
}
else
{
DWORD i, LastId;
CHAR Str[MAX_PATH] = { 0 };
for (i = 0; i < ResGroupData->idCount; i++)
AddResId.push_back((DWORD)ResGroupData->idEntries[i].nID);
EnumResourceNamesA(Module, (LPCSTR)RT_ICON, EnumLastResIdProc, (LONG_PTR)Str);
if (Str[0] == '#')
LastId = atoi(&Str[1]) + 1;
else
LastId = 1;
for (; i < IconDir->idCount; i++, LastId++)
AddResId.push_back(LastId);
}
if (IsGroupExsited)
UnlockResource(ResGroupData);
FreeLibrary(Module);
HANDLE Update = BeginUpdateResourceW(ExePath.c_str(), FALSE);
if (!Update)
return false;
DWORD GroupResSize = 6 + sizeof(GRPICONDIRENTRY)*IconDir->idCount;
PBYTE GroupResData = new(std::nothrow) BYTE[GroupResSize];
LPGRPICONDIR NewGroupDir = (LPGRPICONDIR)GroupResData;
LPGRPICONDIRENTRY NewGroupDirEntry = (LPGRPICONDIRENTRY)(GroupResData + 6);
NewGroupDir->idReserved = IconDir->idReserved;
NewGroupDir->idCount = IconDir->idCount;
NewGroupDir->idType = IconDir->idType;
if (IsGroupExsited)
{
for_each(begin(DelResInfo), end(DelResInfo), [&Update](RESINFO& Info)
{
DeleteResData(Update, Info.ResType, Info.ResName, Info.ResLanguage);
});
DeleteResData(Update, (LPCSTR)RT_GROUP_ICON, GroupName, OriResLang);
}
for (DWORD i = 0; i < IconDir->idCount; i++)
{
memcpy(&NewGroupDirEntry[i], &IconDirEntry[i], sizeof(GRPICONDIRENTRY));
NewGroupDirEntry[i].nID = (WORD)AddResId[i];
LPVOID ItemData = &IconData[0] + IconDirEntry[i].dwImageOffset;
DWORD ItemSize = IconDirEntry[i].dwBytesInRes;
SetResData(Update, (LPCSTR)RT_ICON, MAKEINTRESOURCEA(AddResId[i]), ItemData, ItemSize);
}
SetResData(Update, (LPCSTR)RT_GROUP_ICON, GroupName, (LPVOID&)GroupResData, GroupResSize, 1033);
EndUpdateResource(Update, FALSE);
if (GroupResData)
delete[] GroupResData;
return true;
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/icons/icons.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <Windows.h>
#include <string>
#include <vector>
#include <algorithm>
bool GetIconData(const std::wstring& ExePath, std::string& IconData);
bool SetIconData(const std::wstring& ExePath, std::string& IconData); | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4.c | C | /*
LZ4 - Fast LZ compression algorithm
Copyright (C) 2011-2015, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : http://code.google.com/p/lz4
- LZ4 source mirror : https://github.com/Cyan4973/lz4
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
/**************************************
Tuning parameters
**************************************/
/*
* HEAPMODE :
* Select how default compression functions will allocate memory for their hash table,
* in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
*/
#define HEAPMODE 0
/*
* CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS :
* By default, the source code expects the compiler to correctly optimize
* 4-bytes and 8-bytes read on architectures able to handle it efficiently.
* This is not always the case. In some circumstances (ARM notably),
* the compiler will issue cautious code even when target is able to correctly handle unaligned memory accesses.
*
* You can force the compiler to use unaligned memory access by uncommenting the line below.
* One of the below scenarios will happen :
* 1 - Your target CPU correctly handle unaligned access, and was not well optimized by compiler (good case).
* You will witness large performance improvements (+50% and up).
* Keep the line uncommented and send a word to upstream (https://groups.google.com/forum/#!forum/lz4c)
* The goal is to automatically detect such situations by adding your target CPU within an exception list.
* 2 - Your target CPU correctly handle unaligned access, and was already already optimized by compiler
* No change will be experienced.
* 3 - Your target CPU inefficiently handle unaligned access.
* You will experience a performance loss. Comment back the line.
* 4 - Your target CPU does not handle unaligned access.
* Program will crash.
* If uncommenting results in better performance (case 1)
* please report your configuration to upstream (https://groups.google.com/forum/#!forum/lz4c)
* An automatic detection macro will be added to match your case within future versions of the library.
*/
/* #define CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS 1 */
/**************************************
CPU Feature Detection
**************************************/
/*
* Automated efficient unaligned memory access detection
* Based on known hardware architectures
* This list will be updated thanks to feedbacks
*/
#if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \
|| defined(__ARM_FEATURE_UNALIGNED) \
|| defined(__i386__) || defined(__x86_64__) \
|| defined(_M_IX86) || defined(_M_X64) \
|| defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \
|| (defined(_M_ARM) && (_M_ARM >= 7))
# define LZ4_UNALIGNED_ACCESS 1
#else
# define LZ4_UNALIGNED_ACCESS 0
#endif
/*
* LZ4_FORCE_SW_BITCOUNT
* Define this parameter if your target system or compiler does not support hardware bit count
*/
#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */
# define LZ4_FORCE_SW_BITCOUNT
#endif
/**************************************
Compiler Options
**************************************/
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
/* "restrict" is a known keyword */
#else
# define restrict /* Disable restrict */
#endif
#ifdef _MSC_VER /* Visual Studio */
# define FORCE_INLINE static __forceinline
# include <intrin.h>
# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
#else
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
# ifdef __GNUC__
# define FORCE_INLINE static inline __attribute__((always_inline))
# else
# define FORCE_INLINE static inline
# endif
# else
# define FORCE_INLINE static
# endif /* __STDC_VERSION__ */
#endif /* _MSC_VER */
#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
#if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
# define expect(expr,value) (__builtin_expect ((expr),(value)) )
#else
# define expect(expr,value) (expr)
#endif
#define likely(expr) expect((expr) != 0, 1)
#define unlikely(expr) expect((expr) != 0, 0)
/**************************************
Memory routines
**************************************/
#include <stdlib.h> /* malloc, calloc, free */
#define ALLOCATOR(n,s) calloc(n,s)
#define FREEMEM free
#include <string.h> /* memset, memcpy */
#define MEM_INIT memset
/**************************************
Includes
**************************************/
#include "lz4.h"
/**************************************
Basic Types
**************************************/
#if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
# include <stdint.h>
typedef uint8_t BYTE;
typedef uint16_t U16;
typedef uint32_t U32;
typedef int32_t S32;
typedef uint64_t U64;
#else
typedef unsigned char BYTE;
typedef unsigned short U16;
typedef unsigned int U32;
typedef signed int S32;
typedef unsigned long long U64;
#endif
/**************************************
Reading and writing into memory
**************************************/
#define STEPSIZE sizeof(size_t)
static unsigned LZ4_64bits(void) { return sizeof(void*)==8; }
static unsigned LZ4_isLittleEndian(void)
{
const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
return one.c[0];
}
static U16 LZ4_readLE16(const void* memPtr)
{
if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
return *(U16*)memPtr;
else
{
const BYTE* p = memPtr;
return (U16)((U16)p[0] + (p[1]<<8));
}
}
static void LZ4_writeLE16(void* memPtr, U16 value)
{
if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
{
*(U16*)memPtr = value;
return;
}
else
{
BYTE* p = memPtr;
p[0] = (BYTE) value;
p[1] = (BYTE)(value>>8);
}
}
static U16 LZ4_read16(const void* memPtr)
{
if (LZ4_UNALIGNED_ACCESS)
return *(U16*)memPtr;
else
{
U16 val16;
memcpy(&val16, memPtr, 2);
return val16;
}
}
static U32 LZ4_read32(const void* memPtr)
{
if (LZ4_UNALIGNED_ACCESS)
return *(U32*)memPtr;
else
{
U32 val32;
memcpy(&val32, memPtr, 4);
return val32;
}
}
static U64 LZ4_read64(const void* memPtr)
{
if (LZ4_UNALIGNED_ACCESS)
return *(U64*)memPtr;
else
{
U64 val64;
memcpy(&val64, memPtr, 8);
return val64;
}
}
static size_t LZ4_read_ARCH(const void* p)
{
if (LZ4_64bits())
return (size_t)LZ4_read64(p);
else
return (size_t)LZ4_read32(p);
}
static void LZ4_copy4(void* dstPtr, const void* srcPtr)
{
if (LZ4_UNALIGNED_ACCESS)
{
*(U32*)dstPtr = *(U32*)srcPtr;
return;
}
memcpy(dstPtr, srcPtr, 4);
}
static void LZ4_copy8(void* dstPtr, const void* srcPtr)
{
#if GCC_VERSION!=409 /* disabled on GCC 4.9, as it generates invalid opcode (crash) */
if (LZ4_UNALIGNED_ACCESS)
{
if (LZ4_64bits())
*(U64*)dstPtr = *(U64*)srcPtr;
else
((U32*)dstPtr)[0] = ((U32*)srcPtr)[0],
((U32*)dstPtr)[1] = ((U32*)srcPtr)[1];
return;
}
#endif
memcpy(dstPtr, srcPtr, 8);
}
/* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */
static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
{
BYTE* d = dstPtr;
const BYTE* s = srcPtr;
BYTE* e = dstEnd;
do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);
}
/**************************************
Common Constants
**************************************/
#define MINMATCH 4
#define COPYLENGTH 8
#define LASTLITERALS 5
#define MFLIMIT (COPYLENGTH+MINMATCH)
static const int LZ4_minLength = (MFLIMIT+1);
#define KB *(1 <<10)
#define MB *(1 <<20)
#define GB *(1U<<30)
#define MAXD_LOG 16
#define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
#define ML_BITS 4
#define ML_MASK ((1U<<ML_BITS)-1)
#define RUN_BITS (8-ML_BITS)
#define RUN_MASK ((1U<<RUN_BITS)-1)
/**************************************
Common Utils
**************************************/
#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
/********************************
Common functions
********************************/
static unsigned LZ4_NbCommonBytes (register size_t val)
{
if (LZ4_isLittleEndian())
{
if (LZ4_64bits())
{
# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r = 0;
_BitScanForward64( &r, (U64)val );
return (int)(r>>3);
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
return (__builtin_ctzll((U64)val) >> 3);
# else
static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
# endif
}
else /* 32 bits */
{
# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r;
_BitScanForward( &r, (U32)val );
return (int)(r>>3);
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
return (__builtin_ctz((U32)val) >> 3);
# else
static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
# endif
}
}
else /* Big Endian CPU */
{
if (LZ4_64bits())
{
# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r = 0;
_BitScanReverse64( &r, val );
return (unsigned)(r>>3);
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
return (__builtin_clzll(val) >> 3);
# else
unsigned r;
if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
r += (!val);
return r;
# endif
}
else /* 32 bits */
{
# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r = 0;
_BitScanReverse( &r, (unsigned long)val );
return (unsigned)(r>>3);
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
return (__builtin_clz(val) >> 3);
# else
unsigned r;
if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
r += (!val);
return r;
# endif
}
}
}
static unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
{
const BYTE* const pStart = pIn;
while (likely(pIn<pInLimit-(STEPSIZE-1)))
{
size_t diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
pIn += LZ4_NbCommonBytes(diff);
return (unsigned)(pIn - pStart);
}
if (LZ4_64bits()) if ((pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
return (unsigned)(pIn - pStart);
}
#ifndef LZ4_COMMONDEFS_ONLY
/**************************************
Local Constants
**************************************/
#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
#define HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
#define HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
/**************************************
Local Utils
**************************************/
int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
/**************************************
Local Structures and types
**************************************/
typedef struct {
U32 hashTable[HASH_SIZE_U32];
U32 currentOffset;
U32 initCheck;
const BYTE* dictionary;
const BYTE* bufferStart;
U32 dictSize;
} LZ4_stream_t_internal;
typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive;
typedef enum { byPtr, byU32, byU16 } tableType_t;
typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
typedef enum { full = 0, partial = 1 } earlyEnd_directive;
/********************************
Compression functions
********************************/
static U32 LZ4_hashSequence(U32 sequence, tableType_t tableType)
{
if (tableType == byU16)
return (((sequence) * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
else
return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
}
static U32 LZ4_hashPosition(const BYTE* p, tableType_t tableType) { return LZ4_hashSequence(LZ4_read32(p), tableType); }
static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
{
switch (tableType)
{
case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
}
}
static void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
{
U32 h = LZ4_hashPosition(p, tableType);
LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
}
static const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
{
if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; }
if (tableType == byU32) { U32* hashTable = (U32*) tableBase; return hashTable[h] + srcBase; }
{ U16* hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
}
static const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
{
U32 h = LZ4_hashPosition(p, tableType);
return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
}
static int LZ4_compress_generic(
void* ctx,
const char* source,
char* dest,
int inputSize,
int maxOutputSize,
limitedOutput_directive outputLimited,
tableType_t tableType,
dict_directive dict,
dictIssue_directive dictIssue)
{
LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx;
const BYTE* ip = (const BYTE*) source;
const BYTE* base;
const BYTE* lowLimit;
const BYTE* const lowRefLimit = ip - dictPtr->dictSize;
const BYTE* const dictionary = dictPtr->dictionary;
const BYTE* const dictEnd = dictionary + dictPtr->dictSize;
const size_t dictDelta = dictEnd - (const BYTE*)source;
const BYTE* anchor = (const BYTE*) source;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = iend - LASTLITERALS;
BYTE* op = (BYTE*) dest;
BYTE* const olimit = op + maxOutputSize;
U32 forwardH;
size_t refDelta=0;
/* Init conditions */
if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
switch(dict)
{
case noDict:
default:
base = (const BYTE*)source;
lowLimit = (const BYTE*)source;
break;
case withPrefix64k:
base = (const BYTE*)source - dictPtr->currentOffset;
lowLimit = (const BYTE*)source - dictPtr->dictSize;
break;
case usingExtDict:
base = (const BYTE*)source - dictPtr->currentOffset;
lowLimit = (const BYTE*)source;
break;
}
if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
/* First Byte */
LZ4_putPosition(ip, ctx, tableType, base);
ip++; forwardH = LZ4_hashPosition(ip, tableType);
/* Main Loop */
for ( ; ; )
{
const BYTE* match;
BYTE* token;
{
const BYTE* forwardIp = ip;
unsigned step=1;
unsigned searchMatchNb = (1U << LZ4_skipTrigger);
/* Find a match */
do {
U32 h = forwardH;
ip = forwardIp;
forwardIp += step;
step = searchMatchNb++ >> LZ4_skipTrigger;
if (unlikely(forwardIp > mflimit)) goto _last_literals;
match = LZ4_getPositionOnHash(h, ctx, tableType, base);
if (dict==usingExtDict)
{
if (match<(const BYTE*)source)
{
refDelta = dictDelta;
lowLimit = dictionary;
}
else
{
refDelta = 0;
lowLimit = (const BYTE*)source;
}
}
forwardH = LZ4_hashPosition(forwardIp, tableType);
LZ4_putPositionOnHash(ip, h, ctx, tableType, base);
} while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)
|| ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
|| (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );
}
/* Catch up */
while ((ip>anchor) && (match+refDelta > lowLimit) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }
{
/* Encode Literal length */
unsigned litLength = (unsigned)(ip - anchor);
token = op++;
if ((outputLimited) && (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
return 0; /* Check output limit */
if (litLength>=RUN_MASK)
{
int len = (int)litLength-RUN_MASK;
*token=(RUN_MASK<<ML_BITS);
for(; len >= 255 ; len-=255) *op++ = 255;
*op++ = (BYTE)len;
}
else *token = (BYTE)(litLength<<ML_BITS);
/* Copy Literals */
LZ4_wildCopy(op, anchor, op+litLength);
op+=litLength;
}
_next_match:
/* Encode Offset */
LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
/* Encode MatchLength */
{
unsigned matchLength;
if ((dict==usingExtDict) && (lowLimit==dictionary))
{
const BYTE* limit;
match += refDelta;
limit = ip + (dictEnd-match);
if (limit > matchlimit) limit = matchlimit;
matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
ip += MINMATCH + matchLength;
if (ip==limit)
{
unsigned more = LZ4_count(ip, (const BYTE*)source, matchlimit);
matchLength += more;
ip += more;
}
}
else
{
matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
ip += MINMATCH + matchLength;
}
if ((outputLimited) && (unlikely(op + (1 + LASTLITERALS) + (matchLength>>8) > olimit)))
return 0; /* Check output limit */
if (matchLength>=ML_MASK)
{
*token += ML_MASK;
matchLength -= ML_MASK;
for (; matchLength >= 510 ; matchLength-=510) { *op++ = 255; *op++ = 255; }
if (matchLength >= 255) { matchLength-=255; *op++ = 255; }
*op++ = (BYTE)matchLength;
}
else *token += (BYTE)(matchLength);
}
anchor = ip;
/* Test end of chunk */
if (ip > mflimit) break;
/* Fill table */
LZ4_putPosition(ip-2, ctx, tableType, base);
/* Test next position */
match = LZ4_getPosition(ip, ctx, tableType, base);
if (dict==usingExtDict)
{
if (match<(const BYTE*)source)
{
refDelta = dictDelta;
lowLimit = dictionary;
}
else
{
refDelta = 0;
lowLimit = (const BYTE*)source;
}
}
LZ4_putPosition(ip, ctx, tableType, base);
if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1)
&& (match+MAX_DISTANCE>=ip)
&& (LZ4_read32(match+refDelta)==LZ4_read32(ip)) )
{ token=op++; *token=0; goto _next_match; }
/* Prepare next loop */
forwardH = LZ4_hashPosition(++ip, tableType);
}
_last_literals:
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
if ((outputLimited) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))
return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun >= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) (((char*)op)-dest);
}
int LZ4_compress(const char* source, char* dest, int inputSize)
{
#if (HEAPMODE)
void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
#else
U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
#endif
int result;
if (inputSize < LZ4_64Klimit)
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
else
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
#if (HEAPMODE)
FREEMEM(ctx);
#endif
return result;
}
int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
{
#if (HEAPMODE)
void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
#else
U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
#endif
int result;
if (inputSize < LZ4_64Klimit)
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
else
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
#if (HEAPMODE)
FREEMEM(ctx);
#endif
return result;
}
/*****************************************
Experimental : Streaming functions
*****************************************/
/*
* LZ4_initStream
* Use this function once, to init a newly allocated LZ4_stream_t structure
* Return : 1 if OK, 0 if error
*/
void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
{
MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
}
LZ4_stream_t* LZ4_createStream(void)
{
LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64);
LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
LZ4_resetStream(lz4s);
return lz4s;
}
int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
{
FREEMEM(LZ4_stream);
return (0);
}
int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
{
LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;
const BYTE* p = (const BYTE*)dictionary;
const BYTE* const dictEnd = p + dictSize;
const BYTE* base;
if (dict->initCheck) LZ4_resetStream(LZ4_dict); /* Uninitialized structure detected */
if (dictSize < MINMATCH)
{
dict->dictionary = NULL;
dict->dictSize = 0;
return 0;
}
if (p <= dictEnd - 64 KB) p = dictEnd - 64 KB;
base = p - dict->currentOffset;
dict->dictionary = p;
dict->dictSize = (U32)(dictEnd - p);
dict->currentOffset += dict->dictSize;
while (p <= dictEnd-MINMATCH)
{
LZ4_putPosition(p, dict, byU32, base);
p+=3;
}
return dict->dictSize;
}
static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)
{
if ((LZ4_dict->currentOffset > 0x80000000) ||
((size_t)LZ4_dict->currentOffset > (size_t)src)) /* address space overflow */
{
/* rescale hash table */
U32 delta = LZ4_dict->currentOffset - 64 KB;
const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
int i;
for (i=0; i<HASH_SIZE_U32; i++)
{
if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;
else LZ4_dict->hashTable[i] -= delta;
}
LZ4_dict->currentOffset = 64 KB;
if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
}
}
FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* source, char* dest, int inputSize,
int maxOutputSize, limitedOutput_directive limit)
{
LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_stream;
const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
const BYTE* smallest = (const BYTE*) source;
if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */
if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd;
LZ4_renormDictT(streamPtr, smallest);
/* Check overlapping input/dictionary space */
{
const BYTE* sourceEnd = (const BYTE*) source + inputSize;
if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd))
{
streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
streamPtr->dictionary = dictEnd - streamPtr->dictSize;
}
}
/* prefix mode : source data follows dictionary */
if (dictEnd == (const BYTE*)source)
{
int result;
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, dictSmall);
else
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, noDictIssue);
streamPtr->dictSize += (U32)inputSize;
streamPtr->currentOffset += (U32)inputSize;
return result;
}
/* external dictionary mode */
{
int result;
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, dictSmall);
else
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, noDictIssue);
streamPtr->dictionary = (const BYTE*)source;
streamPtr->dictSize = (U32)inputSize;
streamPtr->currentOffset += (U32)inputSize;
return result;
}
}
int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
{
return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, 0, notLimited);
}
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput);
}
/* Hidden debug function, to force separate dictionary mode */
int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize)
{
LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_dict;
int result;
const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
const BYTE* smallest = dictEnd;
if (smallest > (const BYTE*) source) smallest = (const BYTE*) source;
LZ4_renormDictT((LZ4_stream_t_internal*)LZ4_dict, smallest);
result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue);
streamPtr->dictionary = (const BYTE*)source;
streamPtr->dictSize = (U32)inputSize;
streamPtr->currentOffset += (U32)inputSize;
return result;
}
int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
{
LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;
const BYTE* previousDictEnd = dict->dictionary + dict->dictSize;
if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */
if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
dict->dictionary = (const BYTE*)safeBuffer;
dict->dictSize = (U32)dictSize;
return dictSize;
}
/****************************
Decompression functions
****************************/
/*
* This generic decompression function cover all use cases.
* It shall be instantiated several times, using different sets of directives
* Note that it is essential this generic function is really inlined,
* in order to remove useless branches during compilation optimization.
*/
FORCE_INLINE int LZ4_decompress_generic(
const char* const source,
char* const dest,
int inputSize,
int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */
int endOnInput, /* endOnOutputSize, endOnInputSize */
int partialDecoding, /* full, partial */
int targetOutputSize, /* only used if partialDecoding==partial */
int dict, /* noDict, withPrefix64k, usingExtDict */
const BYTE* const lowPrefix, /* == dest if dict == noDict */
const BYTE* const dictStart, /* only if dict==usingExtDict */
const size_t dictSize /* note : = 0 if noDict */
)
{
/* Local Variables */
const BYTE* restrict ip = (const BYTE*) source;
const BYTE* const iend = ip + inputSize;
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + outputSize;
BYTE* cpy;
BYTE* oexit = op + targetOutputSize;
const BYTE* const lowLimit = lowPrefix - dictSize;
const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
const size_t dec32table[] = {4, 1, 2, 1, 4, 4, 4, 4};
const size_t dec64table[] = {0, 0, 0, (size_t)-1, 0, 1, 2, 3};
const int safeDecode = (endOnInput==endOnInputSize);
const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
/* Special cases */
if ((partialDecoding) && (oexit> oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */
if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1);
/* Main Loop */
while (1)
{
unsigned token;
size_t length;
const BYTE* match;
/* get literal length */
token = *ip++;
if ((length=(token>>ML_BITS)) == RUN_MASK)
{
unsigned s;
do
{
s = *ip++;
length += s;
}
while (likely((endOnInput)?ip<iend-RUN_MASK:1) && (s==255));
if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)(op))) goto _output_error; /* overflow detection */
if ((safeDecode) && unlikely((size_t)(ip+length)<(size_t)(ip))) goto _output_error; /* overflow detection */
}
/* copy literals */
cpy = op+length;
if (((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) )
|| ((!endOnInput) && (cpy>oend-COPYLENGTH)))
{
if (partialDecoding)
{
if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */
if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
}
else
{
if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
}
memcpy(op, ip, length);
ip += length;
op += length;
break; /* Necessarily EOF, due to parsing restrictions */
}
LZ4_wildCopy(op, ip, cpy);
ip += length; op = cpy;
/* get offset */
match = cpy - LZ4_readLE16(ip); ip+=2;
if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside destination buffer */
/* get matchlength */
length = token & ML_MASK;
if (length == ML_MASK)
{
unsigned s;
do
{
if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
s = *ip++;
length += s;
} while (s==255);
if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)op)) goto _output_error; /* overflow detection */
}
length += MINMATCH;
/* check external dictionary */
if ((dict==usingExtDict) && (match < lowPrefix))
{
if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */
if (length <= (size_t)(lowPrefix-match))
{
/* match can be copied as a single segment from external dictionary */
match = dictEnd - (lowPrefix-match);
memcpy(op, match, length);
op += length;
}
else
{
/* match encompass external dictionary and current segment */
size_t copySize = (size_t)(lowPrefix-match);
memcpy(op, dictEnd - copySize, copySize);
op += copySize;
copySize = length - copySize;
if (copySize > (size_t)(op-lowPrefix)) /* overlap within current segment */
{
BYTE* const endOfMatch = op + copySize;
const BYTE* copyFrom = lowPrefix;
while (op < endOfMatch) *op++ = *copyFrom++;
}
else
{
memcpy(op, lowPrefix, copySize);
op += copySize;
}
}
continue;
}
/* copy repeated sequence */
cpy = op + length;
if (unlikely((op-match)<8))
{
const size_t dec64 = dec64table[op-match];
op[0] = match[0];
op[1] = match[1];
op[2] = match[2];
op[3] = match[3];
match += dec32table[op-match];
LZ4_copy4(op+4, match);
op += 8; match -= dec64;
} else { LZ4_copy8(op, match); op+=8; match+=8; }
if (unlikely(cpy>oend-12))
{
if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals */
if (op < oend-8)
{
LZ4_wildCopy(op, match, oend-8);
match += (oend-8) - op;
op = oend-8;
}
while (op<cpy) *op++ = *match++;
}
else
LZ4_wildCopy(op, match, cpy);
op=cpy; /* correction */
}
/* end of decoding */
if (endOnInput)
return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
else
return (int) (((char*)ip)-source); /* Nb of input bytes read */
/* Overflow error detected */
_output_error:
return (int) (-(((char*)ip)-source))-1;
}
int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0);
}
int LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, partial, targetOutputSize, noDict, (BYTE*)dest, NULL, 0);
}
int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
{
return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)(dest - 64 KB), NULL, 64 KB);
}
/* streaming decompression functions */
typedef struct
{
BYTE* externalDict;
size_t extDictSize;
BYTE* prefixEnd;
size_t prefixSize;
} LZ4_streamDecode_t_internal;
/*
* If you prefer dynamic allocation methods,
* LZ4_createStreamDecode()
* provides a pointer (void*) towards an initialized LZ4_streamDecode_t structure.
*/
LZ4_streamDecode_t* LZ4_createStreamDecode(void)
{
LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOCATOR(sizeof(U64), LZ4_STREAMDECODESIZE_U64);
return lz4s;
}
int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
{
FREEMEM(LZ4_stream);
return 0;
}
/*
* LZ4_setStreamDecode
* Use this function to instruct where to find the dictionary
* This function is not necessary if previous data is still available where it was decoded.
* Loading a size of 0 is allowed (same effect as no dictionary).
* Return : 1 if OK, 0 if error
*/
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
{
LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
lz4sd->prefixSize = (size_t) dictSize;
lz4sd->prefixEnd = (BYTE*) dictionary + dictSize;
lz4sd->externalDict = NULL;
lz4sd->extDictSize = 0;
return 1;
}
/*
*_continue() :
These decoding functions allow decompression of multiple blocks in "streaming" mode.
Previously decoded blocks must still be available at the memory position where they were decoded.
If it's not possible, save the relevant part of decoded data into a safe buffer,
and indicate where it stands using LZ4_setStreamDecode()
*/
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
{
LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
int result;
if (lz4sd->prefixEnd == (BYTE*)dest)
{
result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
endOnInputSize, full, 0,
usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
if (result <= 0) return result;
lz4sd->prefixSize += result;
lz4sd->prefixEnd += result;
}
else
{
lz4sd->extDictSize = lz4sd->prefixSize;
lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
endOnInputSize, full, 0,
usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);
if (result <= 0) return result;
lz4sd->prefixSize = result;
lz4sd->prefixEnd = (BYTE*)dest + result;
}
return result;
}
int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)
{
LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
int result;
if (lz4sd->prefixEnd == (BYTE*)dest)
{
result = LZ4_decompress_generic(source, dest, 0, originalSize,
endOnOutputSize, full, 0,
usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
if (result <= 0) return result;
lz4sd->prefixSize += originalSize;
lz4sd->prefixEnd += originalSize;
}
else
{
lz4sd->extDictSize = lz4sd->prefixSize;
lz4sd->externalDict = (BYTE*)dest - lz4sd->extDictSize;
result = LZ4_decompress_generic(source, dest, 0, originalSize,
endOnOutputSize, full, 0,
usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);
if (result <= 0) return result;
lz4sd->prefixSize = originalSize;
lz4sd->prefixEnd = (BYTE*)dest + originalSize;
}
return result;
}
/*
Advanced decoding functions :
*_usingDict() :
These decoding functions work the same as "_continue" ones,
the dictionary must be explicitly provided within parameters
*/
FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize)
{
if (dictSize==0)
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0);
if (dictStart+dictSize == dest)
{
if (dictSize >= (int)(64 KB - 1))
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0);
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0);
}
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
}
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
{
return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize);
}
int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
{
return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize);
}
/* debug function */
int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
}
/***************************************************
Obsolete Functions
***************************************************/
/*
These function names are deprecated and should no longer be used.
They are only provided here for compatibility with older user programs.
- LZ4_uncompress is totally equivalent to LZ4_decompress_fast
- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
*/
int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); }
int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); }
/* Obsolete Streaming functions */
int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
static void LZ4_init(LZ4_stream_t_internal* lz4ds, const BYTE* base)
{
MEM_INIT(lz4ds, 0, LZ4_STREAMSIZE);
lz4ds->bufferStart = base;
}
int LZ4_resetStreamState(void* state, const char* inputBuffer)
{
if ((((size_t)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */
LZ4_init((LZ4_stream_t_internal*)state, (const BYTE*)inputBuffer);
return 0;
}
void* LZ4_create (const char* inputBuffer)
{
void* lz4ds = ALLOCATOR(8, LZ4_STREAMSIZE_U64);
LZ4_init ((LZ4_stream_t_internal*)lz4ds, (const BYTE*)inputBuffer);
return lz4ds;
}
char* LZ4_slideInputBuffer (void* LZ4_Data)
{
LZ4_stream_t_internal* ctx = (LZ4_stream_t_internal*)LZ4_Data;
int dictSize = LZ4_saveDict((LZ4_stream_t*)ctx, (char*)ctx->bufferStart, 64 KB);
return (char*)(ctx->bufferStart + dictSize);
}
/* Obsolete compresson functions using User-allocated state */
int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize)
{
if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
MEM_INIT(state, 0, LZ4_STREAMSIZE);
if (inputSize < LZ4_64Klimit)
return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
else
return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
}
int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)
{
if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
MEM_INIT(state, 0, LZ4_STREAMSIZE);
if (inputSize < LZ4_64Klimit)
return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
else
return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
}
/* Obsolete streaming decompression functions */
int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
}
int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
{
return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
}
#endif /* LZ4_COMMONDEFS_ONLY */
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4.h | C/C++ Header | /*
LZ4 - Fast LZ compression algorithm
Header File
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : http://code.google.com/p/lz4/
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
/*
* lz4.h provides raw compression format functions, for optimal performance and integration into programs.
* If you need to generate data using an inter-operable format (respecting the framing specification),
* please use lz4frame.h instead.
*/
/**************************************
Version
**************************************/
#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
#define LZ4_VERSION_MINOR 5 /* for new (non-breaking) interface capabilities */
#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
int LZ4_versionNumber (void);
/**************************************
Tuning parameter
**************************************/
/*
* LZ4_MEMORY_USAGE :
* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
* Increasing memory usage improves compression ratio
* Reduced memory usage can improve speed, due to cache effect
* Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
*/
#define LZ4_MEMORY_USAGE 14
/**************************************
Simple Functions
**************************************/
int LZ4_compress (const char* source, char* dest, int sourceSize);
int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
/*
LZ4_compress() :
Compresses 'sourceSize' bytes from 'source' into 'dest'.
Destination buffer must be already allocated,
and must be sized to handle worst cases situations (input data not compressible)
Worst case size evaluation is provided by function LZ4_compressBound()
inputSize : Max supported value is LZ4_MAX_INPUT_SIZE
return : the number of bytes written in buffer dest
or 0 if the compression fails
LZ4_decompress_safe() :
compressedSize : is obviously the source size
maxDecompressedSize : is the size of the destination buffer, which must be already allocated.
return : the number of bytes decompressed into the destination buffer (necessarily <= maxDecompressedSize)
If the destination buffer is not large enough, decoding will stop and output an error code (<0).
If the source stream is detected malformed, the function will stop decoding and return a negative result.
This function is protected against buffer overflow exploits,
and never writes outside of output buffer, nor reads outside of input buffer.
It is also protected against malicious data packets.
*/
/**************************************
Advanced Functions
**************************************/
#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
#define LZ4_COMPRESSBOUND(isize) ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
/*
LZ4_compressBound() :
Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
This function is primarily useful for memory allocation purposes (output buffer size).
Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
isize : is the input size. Max supported value is LZ4_MAX_INPUT_SIZE
return : maximum output size in a "worst case" scenario
or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)
*/
int LZ4_compressBound(int isize);
/*
LZ4_compress_limitedOutput() :
Compress 'sourceSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.
If it cannot achieve it, compression will stop, and result of the function will be zero.
This saves time and memory on detecting non-compressible (or barely compressible) data.
This function never writes outside of provided output buffer.
sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
maxOutputSize : is the size of the destination buffer (which must be already allocated)
return : the number of bytes written in buffer 'dest'
or 0 if compression fails
*/
int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
/*
LZ4_compress_withState() :
Same compression functions, but using an externally allocated memory space to store compression state.
Use LZ4_sizeofState() to know how much memory must be allocated,
and then, provide it as 'void* state' to compression functions.
*/
int LZ4_sizeofState(void);
int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
/*
LZ4_decompress_fast() :
originalSize : is the original and therefore uncompressed size
return : the number of bytes read from the source buffer (in other words, the compressed size)
If the source stream is detected malformed, the function will stop decoding and return a negative result.
Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes.
note : This function fully respect memory boundaries for properly formed compressed data.
It is a bit faster than LZ4_decompress_safe().
However, it does not provide any protection against intentionally modified data stream (malicious input).
Use this function in trusted environment only (data to decode comes from a trusted source).
*/
int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
/*
LZ4_decompress_safe_partial() :
This function decompress a compressed block of size 'compressedSize' at position 'source'
into destination buffer 'dest' of size 'maxDecompressedSize'.
The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached,
reducing decompression time.
return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize)
Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller.
Always control how many bytes were decoded.
If the source stream is detected malformed, the function will stop decoding and return a negative result.
This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets
*/
int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize);
/***********************************************
Streaming Compression Functions
***********************************************/
#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(long long))
/*
* LZ4_stream_t
* information structure to track an LZ4 stream.
* important : init this structure content before first use !
* note : only allocated directly the structure if you are statically linking LZ4
* If you are using liblz4 as a DLL, please use below construction methods instead.
*/
typedef struct { long long table[LZ4_STREAMSIZE_U64]; } LZ4_stream_t;
/*
* LZ4_resetStream
* Use this function to init an allocated LZ4_stream_t structure
*/
void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
/*
* LZ4_createStream will allocate and initialize an LZ4_stream_t structure
* LZ4_freeStream releases its memory.
* In the context of a DLL (liblz4), please use these methods rather than the static struct.
* They are more future proof, in case of a change of LZ4_stream_t size.
*/
LZ4_stream_t* LZ4_createStream(void);
int LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);
/*
* LZ4_loadDict
* Use this function to load a static dictionary into LZ4_stream.
* Any previous data will be forgotten, only 'dictionary' will remain in memory.
* Loading a size of 0 is allowed.
* Return : dictionary size, in bytes (necessarily <= 64 KB)
*/
int LZ4_loadDict (LZ4_stream_t* LZ4_streamPtr, const char* dictionary, int dictSize);
/*
* LZ4_compress_continue
* Compress data block 'source', using blocks compressed before as dictionary to improve compression ratio
* Previous data blocks are assumed to still be present at their previous location.
*/
int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
/*
* LZ4_compress_limitedOutput_continue
* Same as before, but also specify a maximum target compressed size (maxOutputSize)
* If objective cannot be met, compression exits, and returns a zero.
*/
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
/*
* LZ4_saveDict
* If previously compressed data block is not guaranteed to remain available at its memory location
* save it into a safer place (char* safeBuffer)
* Note : you don't need to call LZ4_loadDict() afterwards,
* dictionary is immediately usable, you can therefore call again LZ4_compress_continue()
* Return : dictionary size in bytes, or 0 if error
* Note : any dictSize > 64 KB will be interpreted as 64KB.
*/
int LZ4_saveDict (LZ4_stream_t* LZ4_streamPtr, char* safeBuffer, int dictSize);
/************************************************
Streaming Decompression Functions
************************************************/
#define LZ4_STREAMDECODESIZE_U64 4
#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
typedef struct { unsigned long long table[LZ4_STREAMDECODESIZE_U64]; } LZ4_streamDecode_t;
/*
* LZ4_streamDecode_t
* information structure to track an LZ4 stream.
* init this structure content using LZ4_setStreamDecode or memset() before first use !
*
* In the context of a DLL (liblz4) please prefer usage of construction methods below.
* They are more future proof, in case of a change of LZ4_streamDecode_t size in the future.
* LZ4_createStreamDecode will allocate and initialize an LZ4_streamDecode_t structure
* LZ4_freeStreamDecode releases its memory.
*/
LZ4_streamDecode_t* LZ4_createStreamDecode(void);
int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
/*
* LZ4_setStreamDecode
* Use this function to instruct where to find the dictionary.
* Setting a size of 0 is allowed (same effect as reset).
* Return : 1 if OK, 0 if error
*/
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
/*
*_continue() :
These decoding functions allow decompression of multiple blocks in "streaming" mode.
Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB)
If this condition is not possible, save the relevant part of decoded data into a safe buffer,
and indicate where is its new address using LZ4_setStreamDecode()
*/
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
/*
Advanced decoding functions :
*_usingDict() :
These decoding functions work the same as
a combination of LZ4_setDictDecode() followed by LZ4_decompress_x_continue()
They are stand-alone and don't use nor update an LZ4_streamDecode_t structure.
*/
int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
/**************************************
Obsolete Functions
**************************************/
/*
Obsolete decompression functions
These function names are deprecated and should no longer be used.
They are only provided here for compatibility with older user programs.
- LZ4_uncompress is the same as LZ4_decompress_fast
- LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe
These function prototypes are now disabled; uncomment them if you really need them.
It is highly recommended to stop using these functions and migrate to newer ones */
/* int LZ4_uncompress (const char* source, char* dest, int outputSize); */
/* int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); */
/* Obsolete streaming functions; use new streaming interface whenever possible */
void* LZ4_create (const char* inputBuffer);
int LZ4_sizeofStreamState(void);
int LZ4_resetStreamState(void* state, const char* inputBuffer);
char* LZ4_slideInputBuffer (void* state);
/* Obsolete streaming decoding functions */
int LZ4_decompress_safe_withPrefix64k (const char* source, char* dest, int compressedSize, int maxOutputSize);
int LZ4_decompress_fast_withPrefix64k (const char* source, char* dest, int originalSize);
#if defined (__cplusplus)
}
#endif
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4frame.c | C | /*
LZ4 auto-framing library
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : http://code.google.com/p/lz4/
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
/* LZ4F is a stand-alone API to create LZ4-compressed Frames
* fully conformant to specification v1.4.1.
* All related operations, including memory management, are handled by the library.
* */
/**************************************
Compiler Options
**************************************/
#ifdef _MSC_VER /* Visual Studio */
# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
#endif
#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
#ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wmissing-braces" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */
# pragma GCC diagnostic ignored "-Wmissing-field-initializers" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */
#endif
/**************************************
Memory routines
**************************************/
#include <stdlib.h> /* malloc, calloc, free */
#define ALLOCATOR(s) calloc(1,s)
#define FREEMEM free
#include <string.h> /* memset, memcpy, memmove */
#define MEM_INIT memset
/**************************************
Includes
**************************************/
#include "lz4frame_static.h"
#include "lz4.h"
#include "lz4hc.h"
#include "xxhash.h"
/**************************************
Basic Types
**************************************/
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
# include <stdint.h>
typedef uint8_t BYTE;
typedef uint16_t U16;
typedef uint32_t U32;
typedef int32_t S32;
typedef uint64_t U64;
#else
typedef unsigned char BYTE;
typedef unsigned short U16;
typedef unsigned int U32;
typedef signed int S32;
typedef unsigned long long U64;
#endif
/**************************************
Constants
**************************************/
#define KB *(1<<10)
#define MB *(1<<20)
#define GB *(1<<30)
#define _1BIT 0x01
#define _2BITS 0x03
#define _3BITS 0x07
#define _4BITS 0x0F
#define _8BITS 0xFF
#define LZ4F_MAGICNUMBER 0x184D2204U
#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
#define LZ4F_MAXHEADERFRAME_SIZE 7
#define LZ4F_BLOCKSIZEID_DEFAULT max64KB
static const U32 minHClevel = 3;
/**************************************
Structures and local types
**************************************/
typedef struct
{
LZ4F_preferences_t prefs;
U32 version;
U32 cStage;
size_t maxBlockSize;
size_t maxBufferSize;
BYTE* tmpBuff;
BYTE* tmpIn;
size_t tmpInSize;
XXH32_state_t xxh;
void* lz4CtxPtr;
U32 lz4CtxLevel; /* 0: unallocated; 1: LZ4_stream_t; 3: LZ4_streamHC_t */
} LZ4F_cctx_internal_t;
typedef struct
{
LZ4F_frameInfo_t frameInfo;
unsigned version;
unsigned dStage;
size_t maxBlockSize;
size_t maxBufferSize;
const BYTE* srcExpect;
BYTE* tmpIn;
size_t tmpInSize;
size_t tmpInTarget;
BYTE* tmpOutBuffer;
BYTE* dict;
size_t dictSize;
BYTE* tmpOut;
size_t tmpOutSize;
size_t tmpOutStart;
XXH32_state_t xxh;
BYTE header[8];
} LZ4F_dctx_internal_t;
/**************************************
Macros
**************************************/
/**************************************
Error management
**************************************/
#define LZ4F_GENERATE_STRING(STRING) #STRING,
static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) };
U32 LZ4F_isError(LZ4F_errorCode_t code)
{
return (code > (LZ4F_errorCode_t)(-ERROR_maxCode));
}
const char* LZ4F_getErrorName(LZ4F_errorCode_t code)
{
static const char* codeError = "Unspecified error code";
if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)];
return codeError;
}
/**************************************
Private functions
**************************************/
static size_t LZ4F_getBlockSize(unsigned blockSizeID)
{
static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB };
if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
blockSizeID -= 4;
if (blockSizeID > 3) return (size_t)-ERROR_maxBlockSize_invalid;
return blockSizes[blockSizeID];
}
/* unoptimized version; solves endianess & alignment issues */
static void LZ4F_writeLE32 (BYTE* dstPtr, U32 value32)
{
dstPtr[0] = (BYTE)value32;
dstPtr[1] = (BYTE)(value32 >> 8);
dstPtr[2] = (BYTE)(value32 >> 16);
dstPtr[3] = (BYTE)(value32 >> 24);
}
static U32 LZ4F_readLE32 (const BYTE* srcPtr)
{
U32 value32 = srcPtr[0];
value32 += (srcPtr[1]<<8);
value32 += (srcPtr[2]<<16);
value32 += (srcPtr[3]<<24);
return value32;
}
static BYTE LZ4F_headerChecksum (const BYTE* header, size_t length)
{
U32 xxh = XXH32(header, (U32)length, 0);
return (BYTE)(xxh >> 8);
}
/**************************************
Simple compression functions
**************************************/
size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
{
LZ4F_preferences_t prefs = { 0 };
size_t headerSize;
size_t streamSize;
if (preferencesPtr!=NULL) prefs = *preferencesPtr;
{
blockSizeID_t proposedBSID = max64KB;
size_t maxBlockSize = 64 KB;
while (prefs.frameInfo.blockSizeID > proposedBSID)
{
if (srcSize <= maxBlockSize)
{
prefs.frameInfo.blockSizeID = proposedBSID;
break;
}
proposedBSID++;
maxBlockSize <<= 2;
}
}
prefs.autoFlush = 1;
headerSize = 7; /* basic header size (no option) including magic number */
streamSize = LZ4F_compressBound(srcSize, &prefs);
return headerSize + streamSize;
}
/* LZ4F_compressFrame()
* Compress an entire srcBuffer into a valid LZ4 frame, as defined by specification v1.4.1, in a single step.
* The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
* You can get the minimum value of dstMaxSize by using LZ4F_compressFrameBound()
* If this condition is not respected, LZ4F_compressFrame() will fail (result is an errorCode)
* The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
* The result of the function is the number of bytes written into dstBuffer.
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
*/
size_t LZ4F_compressFrame(void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
{
LZ4F_cctx_internal_t cctxI = { 0 }; /* works because no allocation */
LZ4F_preferences_t prefs = { 0 };
LZ4F_compressOptions_t options = { 0 };
LZ4F_errorCode_t errorCode;
BYTE* const dstStart = (BYTE*) dstBuffer;
BYTE* dstPtr = dstStart;
BYTE* const dstEnd = dstStart + dstMaxSize;
cctxI.version = LZ4F_VERSION;
cctxI.maxBufferSize = 5 MB; /* mess with real buffer size to prevent allocation; works because autoflush==1 & stableSrc==1 */
if (preferencesPtr!=NULL) prefs = *preferencesPtr;
{
blockSizeID_t proposedBSID = max64KB;
size_t maxBlockSize = 64 KB;
while (prefs.frameInfo.blockSizeID > proposedBSID)
{
if (srcSize <= maxBlockSize)
{
prefs.frameInfo.blockSizeID = proposedBSID;
break;
}
proposedBSID++;
maxBlockSize <<= 2;
}
}
prefs.autoFlush = 1;
if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID))
prefs.frameInfo.blockMode = blockIndependent; /* no need for linked blocks */
options.stableSrc = 1;
if (dstMaxSize < LZ4F_compressFrameBound(srcSize, &prefs))
return (size_t)-ERROR_dstMaxSize_tooSmall;
errorCode = LZ4F_compressBegin(&cctxI, dstBuffer, dstMaxSize, &prefs); /* write header */
if (LZ4F_isError(errorCode)) return errorCode;
dstPtr += errorCode; /* header size */
dstMaxSize -= errorCode;
errorCode = LZ4F_compressUpdate(&cctxI, dstPtr, dstMaxSize, srcBuffer, srcSize, &options);
if (LZ4F_isError(errorCode)) return errorCode;
dstPtr += errorCode;
errorCode = LZ4F_compressEnd(&cctxI, dstPtr, dstEnd-dstPtr, &options); /* flush last block, and generate suffix */
if (LZ4F_isError(errorCode)) return errorCode;
dstPtr += errorCode;
FREEMEM(cctxI.lz4CtxPtr);
return (dstPtr - dstStart);
}
/***********************************
* Advanced compression functions
* *********************************/
/* LZ4F_createCompressionContext() :
* The first thing to do is to create a compressionContext object, which will be used in all compression operations.
* This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.
* The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.
* The function will provide a pointer to an allocated LZ4F_compressionContext_t object.
* If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.
* Object can release its memory using LZ4F_freeCompressionContext();
*/
LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version)
{
LZ4F_cctx_internal_t* cctxPtr;
cctxPtr = (LZ4F_cctx_internal_t*)ALLOCATOR(sizeof(LZ4F_cctx_internal_t));
if (cctxPtr==NULL) return (LZ4F_errorCode_t)(-ERROR_allocation_failed);
cctxPtr->version = version;
cctxPtr->cStage = 0; /* Next stage : write header */
*LZ4F_compressionContextPtr = (LZ4F_compressionContext_t)cctxPtr;
return OK_NoError;
}
LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext)
{
LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)LZ4F_compressionContext;
FREEMEM(cctxPtr->lz4CtxPtr);
FREEMEM(cctxPtr->tmpBuff);
FREEMEM(LZ4F_compressionContext);
return OK_NoError;
}
/* LZ4F_compressBegin() :
* will write the frame header into dstBuffer.
* dstBuffer must be large enough to accommodate a header (dstMaxSize). Maximum header size is LZ4F_MAXHEADERFRAME_SIZE bytes.
* The result of the function is the number of bytes written into dstBuffer for the header
* or an error code (can be tested using LZ4F_isError())
*/
size_t LZ4F_compressBegin(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_preferences_t* preferencesPtr)
{
LZ4F_preferences_t prefNull = { 0 };
LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
BYTE* const dstStart = (BYTE*)dstBuffer;
BYTE* dstPtr = dstStart;
BYTE* headerStart;
size_t requiredBuffSize;
if (dstMaxSize < LZ4F_MAXHEADERFRAME_SIZE) return (size_t)-ERROR_dstMaxSize_tooSmall;
if (cctxPtr->cStage != 0) return (size_t)-ERROR_GENERIC;
if (preferencesPtr == NULL) preferencesPtr = &prefNull;
cctxPtr->prefs = *preferencesPtr;
/* ctx Management */
{
U32 targetCtxLevel = cctxPtr->prefs.compressionLevel<minHClevel ? 1 : 2;
if (cctxPtr->lz4CtxLevel < targetCtxLevel)
{
FREEMEM(cctxPtr->lz4CtxPtr);
if (cctxPtr->prefs.compressionLevel<minHClevel)
cctxPtr->lz4CtxPtr = (void*)LZ4_createStream();
else
cctxPtr->lz4CtxPtr = (void*)LZ4_createStreamHC();
cctxPtr->lz4CtxLevel = targetCtxLevel;
}
}
/* Buffer Management */
if (cctxPtr->prefs.frameInfo.blockSizeID == 0) cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID);
requiredBuffSize = cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == blockLinked) * 128 KB);
if (preferencesPtr->autoFlush)
requiredBuffSize = (cctxPtr->prefs.frameInfo.blockMode == blockLinked) * 64 KB; /* just needs dict */
if (cctxPtr->maxBufferSize < requiredBuffSize)
{
cctxPtr->maxBufferSize = requiredBuffSize;
FREEMEM(cctxPtr->tmpBuff);
cctxPtr->tmpBuff = (BYTE*)ALLOCATOR(requiredBuffSize);
if (cctxPtr->tmpBuff == NULL) return (size_t)-ERROR_allocation_failed;
}
cctxPtr->tmpIn = cctxPtr->tmpBuff;
cctxPtr->tmpInSize = 0;
XXH32_reset(&(cctxPtr->xxh), 0);
if (cctxPtr->prefs.compressionLevel<minHClevel)
LZ4_resetStream((LZ4_stream_t*)(cctxPtr->lz4CtxPtr));
else
LZ4_resetStreamHC((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), cctxPtr->prefs.compressionLevel);
/* Magic Number */
LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);
dstPtr += 4;
headerStart = dstPtr;
/* FLG Byte */
*dstPtr++ = ((1 & _2BITS) << 6) /* Version('01') */
+ ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5) /* Block mode */
+ (char)((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2); /* Stream checksum */
/* BD Byte */
*dstPtr++ = (char)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4);
/* CRC Byte */
*dstPtr++ = LZ4F_headerChecksum(headerStart, 2);
cctxPtr->cStage = 1; /* header written, wait for data block */
return (dstPtr - dstStart);
}
/* LZ4F_compressBound() : gives the size of Dst buffer given a srcSize to handle worst case situations.
* The LZ4F_frameInfo_t structure is optional :
* you can provide NULL as argument, all preferences will then be set to default.
* */
size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
{
const LZ4F_preferences_t prefsNull = { 0 };
const LZ4F_preferences_t* prefsPtr = (preferencesPtr==NULL) ? &prefsNull : preferencesPtr;
blockSizeID_t bid = prefsPtr->frameInfo.blockSizeID;
size_t blockSize = LZ4F_getBlockSize(bid);
unsigned nbBlocks = (unsigned)(srcSize / blockSize) + 1;
size_t lastBlockSize = prefsPtr->autoFlush ? srcSize % blockSize : blockSize;
size_t blockInfo = 4; /* default, without block CRC option */
size_t frameEnd = 4 + (prefsPtr->frameInfo.contentChecksumFlag*4);
size_t result = (blockInfo * nbBlocks) + (blockSize * (nbBlocks-1)) + lastBlockSize + frameEnd;
return result;
}
typedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level);
static size_t LZ4F_compressBlock(void* dst, const void* src, size_t srcSize, compressFunc_t compress, void* lz4ctx, int level)
{
/* compress one block */
BYTE* cSizePtr = (BYTE*)dst;
U32 cSize;
cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+4), (int)(srcSize), (int)(srcSize-1), level);
LZ4F_writeLE32(cSizePtr, cSize);
if (cSize == 0) /* compression failed */
{
cSize = (U32)srcSize;
LZ4F_writeLE32(cSizePtr, cSize + LZ4F_BLOCKUNCOMPRESSED_FLAG);
memcpy(cSizePtr+4, src, srcSize);
}
return cSize + 4;
}
static int LZ4F_localLZ4_compress_limitedOutput_withState(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level)
{
(void) level;
return LZ4_compress_limitedOutput_withState(ctx, src, dst, srcSize, dstSize);
}
static int LZ4F_localLZ4_compress_limitedOutput_continue(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level)
{
(void) level;
return LZ4_compress_limitedOutput_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstSize);
}
static int LZ4F_localLZ4_compressHC_limitedOutput_continue(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level)
{
(void) level;
return LZ4_compressHC_limitedOutput_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstSize);
}
static compressFunc_t LZ4F_selectCompression(blockMode_t blockMode, U32 level)
{
if (level < minHClevel)
{
if (blockMode == blockIndependent) return LZ4F_localLZ4_compress_limitedOutput_withState;
return LZ4F_localLZ4_compress_limitedOutput_continue;
}
if (blockMode == blockIndependent) return LZ4_compressHC2_limitedOutput_withStateHC;
return LZ4F_localLZ4_compressHC_limitedOutput_continue;
}
static int LZ4F_localSaveDict(LZ4F_cctx_internal_t* cctxPtr)
{
if (cctxPtr->prefs.compressionLevel < minHClevel)
return LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);
return LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);
}
typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus;
/* LZ4F_compressUpdate()
* LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
* The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
* If this condition is not respected, LZ4F_compress() will fail (result is an errorCode)
* You can get the minimum value of dstMaxSize by using LZ4F_compressBound()
* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
* The result of the function is the number of bytes written into dstBuffer : it can be zero, meaning input data was just buffered.
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
*/
size_t LZ4F_compressUpdate(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr)
{
LZ4F_compressOptions_t cOptionsNull = { 0 };
LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
size_t blockSize = cctxPtr->maxBlockSize;
const BYTE* srcPtr = (const BYTE*)srcBuffer;
const BYTE* const srcEnd = srcPtr + srcSize;
BYTE* const dstStart = (BYTE*)dstBuffer;
BYTE* dstPtr = dstStart;
LZ4F_lastBlockStatus lastBlockCompressed = notDone;
compressFunc_t compress;
if (cctxPtr->cStage != 1) return (size_t)-ERROR_GENERIC;
if (dstMaxSize < LZ4F_compressBound(srcSize, &(cctxPtr->prefs))) return (size_t)-ERROR_dstMaxSize_tooSmall;
if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;
/* select compression function */
compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel);
/* complete tmp buffer */
if (cctxPtr->tmpInSize > 0) /* some data already within tmp buffer */
{
size_t sizeToCopy = blockSize - cctxPtr->tmpInSize;
if (sizeToCopy > srcSize)
{
/* add src to tmpIn buffer */
memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize);
srcPtr = srcEnd;
cctxPtr->tmpInSize += srcSize;
/* still needs some CRC */
}
else
{
/* complete tmpIn block and then compress it */
lastBlockCompressed = fromTmpBuffer;
memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy);
srcPtr += sizeToCopy;
dstPtr += LZ4F_compressBlock(dstPtr, cctxPtr->tmpIn, blockSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);
if (cctxPtr->prefs.frameInfo.blockMode==blockLinked) cctxPtr->tmpIn += blockSize;
cctxPtr->tmpInSize = 0;
}
}
while ((size_t)(srcEnd - srcPtr) >= blockSize)
{
/* compress full block */
lastBlockCompressed = fromSrcBuffer;
dstPtr += LZ4F_compressBlock(dstPtr, srcPtr, blockSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);
srcPtr += blockSize;
}
if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd))
{
/* compress remaining input < blockSize */
lastBlockCompressed = fromSrcBuffer;
dstPtr += LZ4F_compressBlock(dstPtr, srcPtr, srcEnd - srcPtr, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);
srcPtr = srcEnd;
}
/* preserve dictionary if necessary */
if ((cctxPtr->prefs.frameInfo.blockMode==blockLinked) && (lastBlockCompressed==fromSrcBuffer))
{
if (compressOptionsPtr->stableSrc)
{
cctxPtr->tmpIn = cctxPtr->tmpBuff;
}
else
{
int realDictSize = LZ4F_localSaveDict(cctxPtr);
if (realDictSize==0) return (size_t)-ERROR_GENERIC;
cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize;
}
}
/* keep tmpIn within limits */
if ((cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize) /* necessarily blockLinked && lastBlockCompressed==fromTmpBuffer */
&& !(cctxPtr->prefs.autoFlush))
{
LZ4F_localSaveDict(cctxPtr);
cctxPtr->tmpIn = cctxPtr->tmpBuff + 64 KB;
}
/* some input data left, necessarily < blockSize */
if (srcPtr < srcEnd)
{
/* fill tmp buffer */
size_t sizeToCopy = srcEnd - srcPtr;
memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy);
cctxPtr->tmpInSize = sizeToCopy;
}
if (cctxPtr->prefs.frameInfo.contentChecksumFlag == contentChecksumEnabled)
XXH32_update(&(cctxPtr->xxh), srcBuffer, (unsigned)srcSize);
return dstPtr - dstStart;
}
/* LZ4F_flush()
* Should you need to create compressed data immediately, without waiting for a block to be filled,
* you can call LZ4_flush(), which will immediately compress any remaining data stored within compressionContext.
* The result of the function is the number of bytes written into dstBuffer
* (it can be zero, this means there was no data left within compressionContext)
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
*/
size_t LZ4F_flush(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr)
{
LZ4F_compressOptions_t cOptionsNull = { 0 };
LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
BYTE* const dstStart = (BYTE*)dstBuffer;
BYTE* dstPtr = dstStart;
compressFunc_t compress;
if (cctxPtr->tmpInSize == 0) return 0; /* nothing to flush */
if (cctxPtr->cStage != 1) return (size_t)-ERROR_GENERIC;
if (dstMaxSize < (cctxPtr->tmpInSize + 16)) return (size_t)-ERROR_dstMaxSize_tooSmall;
if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;
(void)compressOptionsPtr; /* not yet useful */
/* select compression function */
compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel);
/* compress tmp buffer */
dstPtr += LZ4F_compressBlock(dstPtr, cctxPtr->tmpIn, cctxPtr->tmpInSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);
if (cctxPtr->prefs.frameInfo.blockMode==blockLinked) cctxPtr->tmpIn += cctxPtr->tmpInSize;
cctxPtr->tmpInSize = 0;
/* keep tmpIn within limits */
if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)) /* necessarily blockLinked */
{
LZ4F_localSaveDict(cctxPtr);
cctxPtr->tmpIn = cctxPtr->tmpBuff + 64 KB;
}
return dstPtr - dstStart;
}
/* LZ4F_compressEnd()
* When you want to properly finish the compressed frame, just call LZ4F_compressEnd().
* It will flush whatever data remained within compressionContext (like LZ4_flush())
* but also properly finalize the frame, with an endMark and a checksum.
* The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
* compressionContext can then be used again, starting with LZ4F_compressBegin(). The preferences will remain the same.
*/
size_t LZ4F_compressEnd(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr)
{
LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
BYTE* const dstStart = (BYTE*)dstBuffer;
BYTE* dstPtr = dstStart;
size_t errorCode;
errorCode = LZ4F_flush(compressionContext, dstBuffer, dstMaxSize, compressOptionsPtr);
if (LZ4F_isError(errorCode)) return errorCode;
dstPtr += errorCode;
LZ4F_writeLE32(dstPtr, 0);
dstPtr+=4; /* endMark */
if (cctxPtr->prefs.frameInfo.contentChecksumFlag == contentChecksumEnabled)
{
U32 xxh = XXH32_digest(&(cctxPtr->xxh));
LZ4F_writeLE32(dstPtr, xxh);
dstPtr+=4; /* content Checksum */
}
cctxPtr->cStage = 0; /* state is now re-usable (with identical preferences) */
return dstPtr - dstStart;
}
/***********************************
* Decompression functions
* *********************************/
/* Resource management */
/* LZ4F_createDecompressionContext() :
* The first thing to do is to create a decompressionContext object, which will be used in all decompression operations.
* This is achieved using LZ4F_createDecompressionContext().
* The function will provide a pointer to a fully allocated and initialized LZ4F_decompressionContext object.
* If the result LZ4F_errorCode_t is not zero, there was an error during context creation.
* Object can release its memory using LZ4F_freeDecompressionContext();
*/
LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_compressionContext_t* LZ4F_decompressionContextPtr, unsigned versionNumber)
{
LZ4F_dctx_internal_t* dctxPtr;
dctxPtr = ALLOCATOR(sizeof(LZ4F_dctx_internal_t));
if (dctxPtr==NULL) return (LZ4F_errorCode_t)-ERROR_GENERIC;
dctxPtr->version = versionNumber;
*LZ4F_decompressionContextPtr = (LZ4F_compressionContext_t)dctxPtr;
return OK_NoError;
}
LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_compressionContext_t LZ4F_decompressionContext)
{
LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)LZ4F_decompressionContext;
FREEMEM(dctxPtr->tmpIn);
FREEMEM(dctxPtr->tmpOutBuffer);
FREEMEM(dctxPtr);
return OK_NoError;
}
/* Decompression */
static size_t LZ4F_decodeHeader(LZ4F_dctx_internal_t* dctxPtr, const BYTE* srcPtr, size_t srcSize)
{
BYTE FLG, BD, HC;
unsigned version, blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictFlag, blockSizeID;
size_t bufferNeeded;
/* need to decode header to get frameInfo */
if (srcSize < 7) return (size_t)-ERROR_GENERIC; /* minimal header size */
/* control magic number */
if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) return (size_t)-ERROR_GENERIC;
srcPtr += 4;
/* Flags */
FLG = srcPtr[0];
version = (FLG>>6)&_2BITS;
blockMode = (FLG>>5) & _1BIT;
blockChecksumFlag = (FLG>>4) & _1BIT;
contentSizeFlag = (FLG>>3) & _1BIT;
contentChecksumFlag = (FLG>>2) & _1BIT;
dictFlag = (FLG>>0) & _1BIT;
BD = srcPtr[1];
blockSizeID = (BD>>4) & _3BITS;
/* check */
HC = LZ4F_headerChecksum(srcPtr, 2);
if (HC != srcPtr[2]) return (size_t)-ERROR_GENERIC; /* Bad header checksum error */
/* validate */
if (version != 1) return (size_t)-ERROR_GENERIC; /* Version Number, only supported value */
if (blockChecksumFlag != 0) return (size_t)-ERROR_GENERIC; /* Only supported value for the time being */
if (contentSizeFlag != 0) return (size_t)-ERROR_GENERIC; /* Only supported value for the time being */
if (((FLG>>1)&_1BIT) != 0) return (size_t)-ERROR_GENERIC; /* Reserved bit */
if (dictFlag != 0) return (size_t)-ERROR_GENERIC; /* Only supported value for the time being */
if (((BD>>7)&_1BIT) != 0) return (size_t)-ERROR_GENERIC; /* Reserved bit */
if (blockSizeID < 4) return (size_t)-ERROR_GENERIC; /* Only supported values for the time being */
if (((BD>>0)&_4BITS) != 0) return (size_t)-ERROR_GENERIC; /* Reserved bits */
/* save */
dctxPtr->frameInfo.blockMode = blockMode;
dctxPtr->frameInfo.contentChecksumFlag = contentChecksumFlag;
dctxPtr->frameInfo.blockSizeID = blockSizeID;
dctxPtr->maxBlockSize = LZ4F_getBlockSize(blockSizeID);
/* init */
if (contentChecksumFlag) XXH32_reset(&(dctxPtr->xxh), 0);
/* alloc */
bufferNeeded = dctxPtr->maxBlockSize + ((dctxPtr->frameInfo.blockMode==blockLinked) * 128 KB);
if (bufferNeeded > dctxPtr->maxBufferSize) /* tmp buffers too small */
{
FREEMEM(dctxPtr->tmpIn);
FREEMEM(dctxPtr->tmpOutBuffer);
dctxPtr->maxBufferSize = bufferNeeded;
dctxPtr->tmpIn = ALLOCATOR(dctxPtr->maxBlockSize);
if (dctxPtr->tmpIn == NULL) return (size_t)-ERROR_GENERIC;
dctxPtr->tmpOutBuffer= ALLOCATOR(dctxPtr->maxBufferSize);
if (dctxPtr->tmpOutBuffer== NULL) return (size_t)-ERROR_GENERIC;
}
dctxPtr->tmpInSize = 0;
dctxPtr->tmpInTarget = 0;
dctxPtr->dict = dctxPtr->tmpOutBuffer;
dctxPtr->dictSize = 0;
dctxPtr->tmpOut = dctxPtr->tmpOutBuffer;
dctxPtr->tmpOutStart = 0;
dctxPtr->tmpOutSize = 0;
return 7;
}
typedef enum { dstage_getHeader=0, dstage_storeHeader, dstage_decodeHeader,
dstage_getCBlockSize, dstage_storeCBlockSize, dstage_decodeCBlockSize,
dstage_copyDirect,
dstage_getCBlock, dstage_storeCBlock, dstage_decodeCBlock,
dstage_decodeCBlock_intoDst, dstage_decodeCBlock_intoTmp, dstage_flushOut,
dstage_getSuffix, dstage_storeSuffix, dstage_checkSuffix
} dStage_t;
/* LZ4F_getFrameInfo()
* This function decodes frame header information, such as blockSize.
* It is optional : you could start by calling directly LZ4F_decompress() instead.
* The objective is to extract header information without starting decompression, typically for allocation purposes.
* LZ4F_getFrameInfo() can also be used *after* starting decompression, on a valid LZ4F_decompressionContext_t.
* The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
* You are expected to resume decompression from where it stopped (srcBuffer + *srcSizePtr)
* The function result is an hint of the better srcSize to use for next call to LZ4F_decompress,
* or an error code which can be tested using LZ4F_isError().
*/
LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_decompressionContext_t decompressionContext, LZ4F_frameInfo_t* frameInfoPtr, const void* srcBuffer, size_t* srcSizePtr)
{
LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)decompressionContext;
if (dctxPtr->dStage == dstage_getHeader)
{
LZ4F_errorCode_t errorCode = LZ4F_decodeHeader(dctxPtr, srcBuffer, *srcSizePtr);
if (LZ4F_isError(errorCode)) return errorCode;
*srcSizePtr = errorCode;
*frameInfoPtr = dctxPtr->frameInfo;
dctxPtr->srcExpect = NULL;
dctxPtr->dStage = dstage_getCBlockSize;
return 4;
}
/* frameInfo already decoded */
*srcSizePtr = 0;
*frameInfoPtr = dctxPtr->frameInfo;
return 0;
}
static int LZ4F_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize)
{
(void)dictStart;
(void)dictSize;
return LZ4_decompress_safe (source, dest, compressedSize, maxDecompressedSize);
}
static void LZ4F_updateDict(LZ4F_dctx_internal_t* dctxPtr, const BYTE* dstPtr, size_t dstSize, const BYTE* dstPtr0, unsigned withinTmp)
{
if (dctxPtr->dictSize==0)
dctxPtr->dict = (BYTE*)dstPtr; /* priority to dictionary continuity */
if (dctxPtr->dict + dctxPtr->dictSize == dstPtr) /* dictionary continuity */
{
dctxPtr->dictSize += dstSize;
return;
}
if (dstPtr - dstPtr0 + dstSize >= 64 KB) /* dstBuffer large enough to become dictionary */
{
dctxPtr->dict = (BYTE*)dstPtr0;
dctxPtr->dictSize = dstPtr - dstPtr0 + dstSize;
return;
}
if ((withinTmp) && (dctxPtr->dict == dctxPtr->tmpOutBuffer))
{
/* assumption : dctxPtr->dict + dctxPtr->dictSize == dctxPtr->tmpOut + dctxPtr->tmpOutStart */
dctxPtr->dictSize += dstSize;
return;
}
if (withinTmp) /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */
{
#if 0
size_t savedDictSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;
memcpy(dctxPtr->tmpOutBuffer, dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart- savedDictSize, savedDictSize);
dctxPtr->dict = dctxPtr->tmpOutBuffer;
dctxPtr->dictSize = savedDictSize + dctxPtr->tmpOutStart + dstSize;
return;
#else
size_t preserveSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;
size_t copySize = 64 KB - dctxPtr->tmpOutSize;
BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart;
if (dctxPtr->tmpOutSize > 64 KB) copySize = 0;
if (copySize > preserveSize) copySize = preserveSize;
memcpy(dctxPtr->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
dctxPtr->dict = dctxPtr->tmpOutBuffer;
dctxPtr->dictSize = preserveSize + dctxPtr->tmpOutStart + dstSize;
return;
#endif
}
if (dctxPtr->dict == dctxPtr->tmpOutBuffer) /* copy dst into tmp to complete dict */
{
if (dctxPtr->dictSize + dstSize > dctxPtr->maxBufferSize) /* tmp buffer not large enough */
{
size_t preserveSize = 64 KB - dstSize; /* note : dstSize < 64 KB */
memcpy(dctxPtr->dict, dctxPtr->dict + dctxPtr->dictSize - preserveSize, preserveSize);
dctxPtr->dictSize = preserveSize;
}
memcpy(dctxPtr->dict + dctxPtr->dictSize, dstPtr, dstSize);
dctxPtr->dictSize += dstSize;
return;
}
/* join dict & dest into tmp */
{
size_t preserveSize = 64 KB - dstSize; /* note : dstSize < 64 KB */
if (preserveSize > dctxPtr->dictSize) preserveSize = dctxPtr->dictSize;
memcpy(dctxPtr->tmpOutBuffer, dctxPtr->dict + dctxPtr->dictSize - preserveSize, preserveSize);
memcpy(dctxPtr->tmpOutBuffer + preserveSize, dstPtr, dstSize);
dctxPtr->dict = dctxPtr->tmpOutBuffer;
dctxPtr->dictSize = preserveSize + dstSize;
}
}
/* LZ4F_decompress()
* Call this function repetitively to regenerate data compressed within srcBuffer.
* The function will attempt to decode *srcSizePtr from srcBuffer, into dstBuffer of maximum size *dstSizePtr.
*
* The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).
*
* The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
* If the number of bytes read is < number of bytes provided, then the decompression operation is not complete.
* You will have to call it again, continuing from where it stopped.
*
* The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.
* Basically, it's the size of the current (or remaining) compressed block + header of next block.
* Respecting the hint provides some boost to performance, since it allows less buffer shuffling.
* Note that this is just a hint, you can always provide any srcSize you want.
* When a frame is fully decoded, the function result will be 0.
* If decompression failed, function result is an error code which can be tested using LZ4F_isError().
*/
size_t LZ4F_decompress(LZ4F_decompressionContext_t decompressionContext,
void* dstBuffer, size_t* dstSizePtr,
const void* srcBuffer, size_t* srcSizePtr,
const LZ4F_decompressOptions_t* decompressOptionsPtr)
{
LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)decompressionContext;
static const LZ4F_decompressOptions_t optionsNull = { 0 };
const BYTE* const srcStart = (const BYTE*)srcBuffer;
const BYTE* const srcEnd = srcStart + *srcSizePtr;
const BYTE* srcPtr = srcStart;
BYTE* const dstStart = (BYTE*)dstBuffer;
BYTE* const dstEnd = dstStart + *dstSizePtr;
BYTE* dstPtr = dstStart;
const BYTE* selectedIn=NULL;
unsigned doAnotherStage = 1;
size_t nextSrcSizeHint = 1;
if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull;
*srcSizePtr = 0;
*dstSizePtr = 0;
/* expect to continue decoding src buffer where it left previously */
if (dctxPtr->srcExpect != NULL)
{
if (srcStart != dctxPtr->srcExpect) return (size_t)-ERROR_GENERIC;
}
/* programmed as a state machine */
while (doAnotherStage)
{
switch(dctxPtr->dStage)
{
case dstage_getHeader:
{
if (srcEnd-srcPtr >= 7)
{
selectedIn = srcPtr;
srcPtr += 7;
dctxPtr->dStage = dstage_decodeHeader;
break;
}
dctxPtr->tmpInSize = 0;
dctxPtr->dStage = dstage_storeHeader;
break;
}
case dstage_storeHeader:
{
size_t sizeToCopy = 7 - dctxPtr->tmpInSize;
if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;
memcpy(dctxPtr->header + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
dctxPtr->tmpInSize += sizeToCopy;
srcPtr += sizeToCopy;
if (dctxPtr->tmpInSize < 7)
{
nextSrcSizeHint = (7 - dctxPtr->tmpInSize) + 4;
doAnotherStage = 0; /* no enough src, wait to get some more */
break;
}
selectedIn = dctxPtr->header;
dctxPtr->dStage = dstage_decodeHeader;
break;
}
case dstage_decodeHeader:
{
LZ4F_errorCode_t errorCode = LZ4F_decodeHeader(dctxPtr, selectedIn, 7);
if (LZ4F_isError(errorCode)) return errorCode;
dctxPtr->dStage = dstage_getCBlockSize;
break;
}
case dstage_getCBlockSize:
{
if ((srcEnd - srcPtr) >= 4)
{
selectedIn = srcPtr;
srcPtr += 4;
dctxPtr->dStage = dstage_decodeCBlockSize;
break;
}
/* not enough input to read cBlockSize field */
dctxPtr->tmpInSize = 0;
dctxPtr->dStage = dstage_storeCBlockSize;
break;
}
case dstage_storeCBlockSize:
{
size_t sizeToCopy = 4 - dctxPtr->tmpInSize;
if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;
memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
srcPtr += sizeToCopy;
dctxPtr->tmpInSize += sizeToCopy;
if (dctxPtr->tmpInSize < 4) /* not enough input to get full cBlockSize; wait for more */
{
nextSrcSizeHint = 4 - dctxPtr->tmpInSize;
doAnotherStage=0;
break;
}
selectedIn = dctxPtr->tmpIn;
dctxPtr->dStage = dstage_decodeCBlockSize;
break;
}
case dstage_decodeCBlockSize:
{
size_t nextCBlockSize = LZ4F_readLE32(selectedIn) & 0x7FFFFFFFU;
if (nextCBlockSize==0) /* frameEnd signal, no more CBlock */
{
dctxPtr->dStage = dstage_getSuffix;
break;
}
if (nextCBlockSize > dctxPtr->maxBlockSize) return (size_t)-ERROR_GENERIC; /* invalid cBlockSize */
dctxPtr->tmpInTarget = nextCBlockSize;
if (LZ4F_readLE32(selectedIn) & LZ4F_BLOCKUNCOMPRESSED_FLAG)
{
dctxPtr->dStage = dstage_copyDirect;
break;
}
dctxPtr->dStage = dstage_getCBlock;
if (dstPtr==dstEnd)
{
nextSrcSizeHint = nextCBlockSize + 4;
doAnotherStage = 0;
}
break;
}
case dstage_copyDirect: /* uncompressed block */
{
size_t sizeToCopy = dctxPtr->tmpInTarget;
if ((size_t)(srcEnd-srcPtr) < sizeToCopy) sizeToCopy = srcEnd - srcPtr; /* not enough input to read full block */
if ((size_t)(dstEnd-dstPtr) < sizeToCopy) sizeToCopy = dstEnd - dstPtr;
memcpy(dstPtr, srcPtr, sizeToCopy);
if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), srcPtr, (U32)sizeToCopy);
/* dictionary management */
if (dctxPtr->frameInfo.blockMode==blockLinked)
LZ4F_updateDict(dctxPtr, dstPtr, sizeToCopy, dstStart, 0);
srcPtr += sizeToCopy;
dstPtr += sizeToCopy;
if (sizeToCopy == dctxPtr->tmpInTarget) /* all copied */
{
dctxPtr->dStage = dstage_getCBlockSize;
break;
}
dctxPtr->tmpInTarget -= sizeToCopy; /* still need to copy more */
nextSrcSizeHint = dctxPtr->tmpInTarget + 4;
doAnotherStage = 0;
break;
}
case dstage_getCBlock: /* entry from dstage_decodeCBlockSize */
{
if ((size_t)(srcEnd-srcPtr) < dctxPtr->tmpInTarget)
{
dctxPtr->tmpInSize = 0;
dctxPtr->dStage = dstage_storeCBlock;
break;
}
selectedIn = srcPtr;
srcPtr += dctxPtr->tmpInTarget;
dctxPtr->dStage = dstage_decodeCBlock;
break;
}
case dstage_storeCBlock:
{
size_t sizeToCopy = dctxPtr->tmpInTarget - dctxPtr->tmpInSize;
if (sizeToCopy > (size_t)(srcEnd-srcPtr)) sizeToCopy = srcEnd-srcPtr;
memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
dctxPtr->tmpInSize += sizeToCopy;
srcPtr += sizeToCopy;
if (dctxPtr->tmpInSize < dctxPtr->tmpInTarget) /* need more input */
{
nextSrcSizeHint = (dctxPtr->tmpInTarget - dctxPtr->tmpInSize) + 4;
doAnotherStage=0;
break;
}
selectedIn = dctxPtr->tmpIn;
dctxPtr->dStage = dstage_decodeCBlock;
break;
}
case dstage_decodeCBlock:
{
if ((size_t)(dstEnd-dstPtr) < dctxPtr->maxBlockSize) /* not enough place into dst : decode into tmpOut */
dctxPtr->dStage = dstage_decodeCBlock_intoTmp;
else
dctxPtr->dStage = dstage_decodeCBlock_intoDst;
break;
}
case dstage_decodeCBlock_intoDst:
{
int (*decoder)(const char*, char*, int, int, const char*, int);
int decodedSize;
if (dctxPtr->frameInfo.blockMode == blockLinked)
decoder = LZ4_decompress_safe_usingDict;
else
decoder = LZ4F_decompress_safe;
decodedSize = decoder((const char*)selectedIn, (char*)dstPtr, (int)dctxPtr->tmpInTarget, (int)dctxPtr->maxBlockSize, (const char*)dctxPtr->dict, (int)dctxPtr->dictSize);
if (decodedSize < 0) return (size_t)-ERROR_GENERIC; /* decompression failed */
if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), dstPtr, decodedSize);
/* dictionary management */
if (dctxPtr->frameInfo.blockMode==blockLinked)
LZ4F_updateDict(dctxPtr, dstPtr, decodedSize, dstStart, 0);
dstPtr += decodedSize;
dctxPtr->dStage = dstage_getCBlockSize;
break;
}
case dstage_decodeCBlock_intoTmp:
{
/* not enough place into dst : decode into tmpOut */
int (*decoder)(const char*, char*, int, int, const char*, int);
int decodedSize;
if (dctxPtr->frameInfo.blockMode == blockLinked)
decoder = LZ4_decompress_safe_usingDict;
else
decoder = LZ4F_decompress_safe;
/* ensure enough place for tmpOut */
if (dctxPtr->frameInfo.blockMode == blockLinked)
{
if (dctxPtr->dict == dctxPtr->tmpOutBuffer)
{
if (dctxPtr->dictSize > 128 KB)
{
memcpy(dctxPtr->dict, dctxPtr->dict + dctxPtr->dictSize - 64 KB, 64 KB);
dctxPtr->dictSize = 64 KB;
}
dctxPtr->tmpOut = dctxPtr->dict + dctxPtr->dictSize;
}
else /* dict not within tmp */
{
size_t reservedDictSpace = dctxPtr->dictSize;
if (reservedDictSpace > 64 KB) reservedDictSpace = 64 KB;
dctxPtr->tmpOut = dctxPtr->tmpOutBuffer + reservedDictSpace;
}
}
/* Decode */
decodedSize = decoder((const char*)selectedIn, (char*)dctxPtr->tmpOut, (int)dctxPtr->tmpInTarget, (int)dctxPtr->maxBlockSize, (const char*)dctxPtr->dict, (int)dctxPtr->dictSize);
if (decodedSize < 0) return (size_t)-ERROR_decompressionFailed; /* decompression failed */
if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), dctxPtr->tmpOut, decodedSize);
dctxPtr->tmpOutSize = decodedSize;
dctxPtr->tmpOutStart = 0;
dctxPtr->dStage = dstage_flushOut;
break;
}
case dstage_flushOut: /* flush decoded data from tmpOut to dstBuffer */
{
size_t sizeToCopy = dctxPtr->tmpOutSize - dctxPtr->tmpOutStart;
if (sizeToCopy > (size_t)(dstEnd-dstPtr)) sizeToCopy = dstEnd-dstPtr;
memcpy(dstPtr, dctxPtr->tmpOut + dctxPtr->tmpOutStart, sizeToCopy);
/* dictionary management */
if (dctxPtr->frameInfo.blockMode==blockLinked)
LZ4F_updateDict(dctxPtr, dstPtr, sizeToCopy, dstStart, 1);
dctxPtr->tmpOutStart += sizeToCopy;
dstPtr += sizeToCopy;
/* end of flush ? */
if (dctxPtr->tmpOutStart == dctxPtr->tmpOutSize)
{
dctxPtr->dStage = dstage_getCBlockSize;
break;
}
nextSrcSizeHint = 4;
doAnotherStage = 0; /* still some data to flush */
break;
}
case dstage_getSuffix:
{
size_t suffixSize = dctxPtr->frameInfo.contentChecksumFlag * 4;
if (suffixSize == 0) /* frame completed */
{
nextSrcSizeHint = 0;
dctxPtr->dStage = dstage_getHeader;
doAnotherStage = 0;
break;
}
if ((srcEnd - srcPtr) >= 4) /* CRC present */
{
selectedIn = srcPtr;
srcPtr += 4;
dctxPtr->dStage = dstage_checkSuffix;
break;
}
dctxPtr->tmpInSize = 0;
dctxPtr->dStage = dstage_storeSuffix;
break;
}
case dstage_storeSuffix:
{
size_t sizeToCopy = 4 - dctxPtr->tmpInSize;
if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;
memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
srcPtr += sizeToCopy;
dctxPtr->tmpInSize += sizeToCopy;
if (dctxPtr->tmpInSize < 4) /* not enough input to read complete suffix */
{
nextSrcSizeHint = 4 - dctxPtr->tmpInSize;
doAnotherStage=0;
break;
}
selectedIn = dctxPtr->tmpIn;
dctxPtr->dStage = dstage_checkSuffix;
break;
}
case dstage_checkSuffix:
{
U32 readCRC = LZ4F_readLE32(selectedIn);
U32 resultCRC = XXH32_digest(&(dctxPtr->xxh));
if (readCRC != resultCRC) return (size_t)-ERROR_checksum_invalid;
nextSrcSizeHint = 0;
dctxPtr->dStage = dstage_getHeader;
doAnotherStage = 0;
break;
}
}
}
/* preserve dictionary within tmp if necessary */
if ( (dctxPtr->frameInfo.blockMode==blockLinked)
&&(dctxPtr->dict != dctxPtr->tmpOutBuffer)
&&(!decompressOptionsPtr->stableDst)
&&((unsigned)(dctxPtr->dStage-1) < (unsigned)(dstage_getSuffix-1))
)
{
if (dctxPtr->dStage == dstage_flushOut)
{
size_t preserveSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;
size_t copySize = 64 KB - dctxPtr->tmpOutSize;
BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart;
if (dctxPtr->tmpOutSize > 64 KB) copySize = 0;
if (copySize > preserveSize) copySize = preserveSize;
memcpy(dctxPtr->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
dctxPtr->dict = dctxPtr->tmpOutBuffer;
dctxPtr->dictSize = preserveSize + dctxPtr->tmpOutStart;
}
else
{
size_t newDictSize = dctxPtr->dictSize;
BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize;
if ((newDictSize) > 64 KB) newDictSize = 64 KB;
memcpy(dctxPtr->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize);
dctxPtr->dict = dctxPtr->tmpOutBuffer;
dctxPtr->dictSize = newDictSize;
dctxPtr->tmpOut = dctxPtr->tmpOutBuffer + newDictSize;
}
}
if (srcPtr<srcEnd) /* function must be called again with following source data */
dctxPtr->srcExpect = srcPtr;
else
dctxPtr->srcExpect = NULL;
*srcSizePtr = (srcPtr - srcStart);
*dstSizePtr = (dstPtr - dstStart);
return nextSrcSizeHint;
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4frame.h | C/C++ Header | /*
LZ4 auto-framing library
Header File
Copyright (C) 2011-2015, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : http://code.google.com/p/lz4/
- LZ4 source mirror : https://github.com/Cyan4973/lz4
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
/* LZ4F is a stand-alone API to create LZ4-compressed frames
* fully conformant to specification v1.4.1.
* All related operations, including memory management, are handled by the library.
* You don't need lz4.h when using lz4frame.h.
* */
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
/**************************************
Includes
**************************************/
#include <stddef.h> /* size_t */
/**************************************
* Error management
* ************************************/
typedef size_t LZ4F_errorCode_t;
unsigned LZ4F_isError(LZ4F_errorCode_t code);
const char* LZ4F_getErrorName(LZ4F_errorCode_t code); /* return error code string; useful for debugging */
/**************************************
* Frame compression types
* ************************************/
typedef enum { LZ4F_default=0, max64KB=4, max256KB=5, max1MB=6, max4MB=7 } blockSizeID_t;
typedef enum { blockLinked=0, blockIndependent} blockMode_t;
typedef enum { noContentChecksum=0, contentChecksumEnabled } contentChecksum_t;
typedef struct {
blockSizeID_t blockSizeID; /* max64KB, max256KB, max1MB, max4MB ; 0 == default */
blockMode_t blockMode; /* blockLinked, blockIndependent ; 0 == default */
contentChecksum_t contentChecksumFlag; /* noContentChecksum, contentChecksumEnabled ; 0 == default */
unsigned reserved[5];
} LZ4F_frameInfo_t;
typedef struct {
LZ4F_frameInfo_t frameInfo;
unsigned compressionLevel; /* 0 == default (fast mode); values above 16 count as 16 */
unsigned autoFlush; /* 1 == always flush : reduce need for tmp buffer */
unsigned reserved[4];
} LZ4F_preferences_t;
/***********************************
* Simple compression function
* *********************************/
size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
size_t LZ4F_compressFrame(void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
/* LZ4F_compressFrame()
* Compress an entire srcBuffer into a valid LZ4 frame, as defined by specification v1.4.1.
* The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
* You can get the minimum value of dstMaxSize by using LZ4F_compressFrameBound()
* If this condition is not respected, LZ4F_compressFrame() will fail (result is an errorCode)
* The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
* The result of the function is the number of bytes written into dstBuffer.
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
*/
/**********************************
* Advanced compression functions
* ********************************/
typedef void* LZ4F_compressionContext_t;
typedef struct {
unsigned stableSrc; /* 1 == src content will remain available on future calls to LZ4F_compress(); avoid saving src content within tmp buffer as future dictionary */
unsigned reserved[3];
} LZ4F_compressOptions_t;
/* Resource Management */
#define LZ4F_VERSION 100
LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version);
LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext);
/* LZ4F_createCompressionContext() :
* The first thing to do is to create a compressionContext object, which will be used in all compression operations.
* This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.
* The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.
* The function will provide a pointer to a fully allocated LZ4F_compressionContext_t object.
* If the result LZ4F_errorCode_t is not zero, there was an error during context creation.
* Object can release its memory using LZ4F_freeCompressionContext();
*/
/* Compression */
size_t LZ4F_compressBegin(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_preferences_t* preferencesPtr);
/* LZ4F_compressBegin() :
* will write the frame header into dstBuffer.
* dstBuffer must be large enough to accommodate a header (dstMaxSize). Maximum header size is 19 bytes.
* The LZ4F_preferences_t structure is optional : you can provide NULL as argument, all preferences will then be set to default.
* The result of the function is the number of bytes written into dstBuffer for the header
* or an error code (can be tested using LZ4F_isError())
*/
size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
/* LZ4F_compressBound() :
* Provides the minimum size of Dst buffer given srcSize to handle worst case situations.
* preferencesPtr is optional : you can provide NULL as argument, all preferences will then be set to default.
* Note that different preferences will produce in different results.
*/
size_t LZ4F_compressUpdate(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr);
/* LZ4F_compressUpdate()
* LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
* The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
* If this condition is not respected, LZ4F_compress() will fail (result is an errorCode)
* You can get the minimum value of dstMaxSize by using LZ4F_compressBound()
* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
* The result of the function is the number of bytes written into dstBuffer : it can be zero, meaning input data was just buffered.
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
*/
size_t LZ4F_flush(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr);
/* LZ4F_flush()
* Should you need to create compressed data immediately, without waiting for a block to be filled,
* you can call LZ4_flush(), which will immediately compress any remaining data buffered within compressionContext.
* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
* The result of the function is the number of bytes written into dstBuffer
* (it can be zero, this means there was no data left within compressionContext)
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
*/
size_t LZ4F_compressEnd(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr);
/* LZ4F_compressEnd()
* When you want to properly finish the compressed frame, just call LZ4F_compressEnd().
* It will flush whatever data remained within compressionContext (like LZ4_flush())
* but also properly finalize the frame, with an endMark and a checksum.
* The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))
* The function outputs an error code if it fails (can be tested using LZ4F_isError())
* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
* compressionContext can then be used again, starting with LZ4F_compressBegin().
*/
/***********************************
* Decompression functions
* *********************************/
typedef void* LZ4F_decompressionContext_t;
typedef struct {
unsigned stableDst; /* guarantee that decompressed data will still be there on next function calls (avoid storage into tmp buffers) */
unsigned reserved[3];
} LZ4F_decompressOptions_t;
/* Resource management */
LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_decompressionContext_t* ctxPtr, unsigned version);
LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_decompressionContext_t ctx);
/* LZ4F_createDecompressionContext() :
* The first thing to do is to create a decompressionContext object, which will be used in all decompression operations.
* This is achieved using LZ4F_createDecompressionContext().
* The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.
* The function will provide a pointer to a fully allocated and initialized LZ4F_decompressionContext_t object.
* If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.
* Object can release its memory using LZ4F_freeDecompressionContext();
*/
/* Decompression */
size_t LZ4F_getFrameInfo(LZ4F_decompressionContext_t ctx,
LZ4F_frameInfo_t* frameInfoPtr,
const void* srcBuffer, size_t* srcSizePtr);
/* LZ4F_getFrameInfo()
* This function decodes frame header information, such as blockSize.
* It is optional : you could start by calling directly LZ4F_decompress() instead.
* The objective is to extract header information without starting decompression, typically for allocation purposes.
* LZ4F_getFrameInfo() can also be used *after* starting decompression, on a valid LZ4F_decompressionContext_t.
* The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
* You are expected to resume decompression from where it stopped (srcBuffer + *srcSizePtr)
* The function result is an hint of how many srcSize bytes LZ4F_decompress() expects for next call,
* or an error code which can be tested using LZ4F_isError().
*/
size_t LZ4F_decompress(LZ4F_decompressionContext_t ctx,
void* dstBuffer, size_t* dstSizePtr,
const void* srcBuffer, size_t* srcSizePtr,
const LZ4F_decompressOptions_t* optionsPtr);
/* LZ4F_decompress()
* Call this function repetitively to regenerate data compressed within srcBuffer.
* The function will attempt to decode *srcSizePtr bytes from srcBuffer, into dstBuffer of maximum size *dstSizePtr.
*
* The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).
*
* The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
* If number of bytes read is < number of bytes provided, then decompression operation is not completed.
* It typically happens when dstBuffer is not large enough to contain all decoded data.
* LZ4F_decompress() must be called again, starting from where it stopped (srcBuffer + *srcSizePtr)
* The function will check this condition, and refuse to continue if it is not respected.
*
* dstBuffer is supposed to be flushed between each call to the function, since its content will be overwritten.
* dst arguments can be changed at will with each consecutive call to the function.
*
* The function result is an hint of how many srcSize bytes LZ4F_decompress() expects for next call.
* Schematically, it's the size of the current (or remaining) compressed block + header of next block.
* Respecting the hint provides some boost to performance, since it does skip intermediate buffers.
* This is just a hint, you can always provide any srcSize you want.
* When a frame is fully decoded, the function result will be 0. (no more data expected)
* If decompression failed, function result is an error code, which can be tested using LZ4F_isError().
*/
#if defined (__cplusplus)
}
#endif
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4frame_static.h | C/C++ Header | /*
LZ4 auto-framing library
Header File for static linking only
Copyright (C) 2011-2015, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : http://code.google.com/p/lz4/
- LZ4 source mirror : https://github.com/Cyan4973/lz4
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
/* lz4frame_static.h should be used solely in the context of static linking.
* */
/**************************************
* Error management
* ************************************/
#define LZ4F_LIST_ERRORS(ITEM) \
ITEM(OK_NoError) ITEM(ERROR_GENERIC) \
ITEM(ERROR_maxBlockSize_invalid) ITEM(ERROR_blockMode_invalid) ITEM(ERROR_contentChecksumFlag_invalid) \
ITEM(ERROR_compressionLevel_invalid) \
ITEM(ERROR_allocation_failed) \
ITEM(ERROR_srcSize_tooLarge) ITEM(ERROR_dstMaxSize_tooSmall) \
ITEM(ERROR_decompressionFailed) \
ITEM(ERROR_checksum_invalid) \
ITEM(ERROR_maxCode)
#define LZ4F_GENERATE_ENUM(ENUM) ENUM,
typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM) } LZ4F_errorCodes; /* enum is exposed, to handle specific errors; compare function result to -enum value */
/**************************************
Includes
**************************************/
#include "lz4frame.h"
#if defined (__cplusplus)
}
#endif
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4hc.c | C | /*
LZ4 HC - High Compression Mode of LZ4
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
- LZ4 source repository : http://code.google.com/p/lz4/
*/
/**************************************
Tuning Parameter
**************************************/
static const int LZ4HC_compressionLevel_default = 8;
/**************************************
Includes
**************************************/
#include "lz4hc.h"
/**************************************
Local Compiler Options
**************************************/
#if defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#if defined (__clang__)
# pragma clang diagnostic ignored "-Wunused-function"
#endif
/**************************************
Common LZ4 definition
**************************************/
#define LZ4_COMMONDEFS_ONLY
#include "lz4.c"
/**************************************
Local Constants
**************************************/
#define DICTIONARY_LOGSIZE 16
#define MAXD (1<<DICTIONARY_LOGSIZE)
#define MAXD_MASK ((U32)(MAXD - 1))
#define HASH_LOG (DICTIONARY_LOGSIZE-1)
#define HASHTABLESIZE (1 << HASH_LOG)
#define HASH_MASK (HASHTABLESIZE - 1)
#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
static const int g_maxCompressionLevel = 16;
/**************************************
Local Types
**************************************/
typedef struct
{
U32 hashTable[HASHTABLESIZE];
U16 chainTable[MAXD];
const BYTE* end; /* next block here to continue on current prefix */
const BYTE* base; /* All index relative to this position */
const BYTE* dictBase; /* alternate base for extDict */
const BYTE* inputBuffer;/* deprecated */
U32 dictLimit; /* below that point, need extDict */
U32 lowLimit; /* below that point, no more dict */
U32 nextToUpdate;
U32 compressionLevel;
} LZ4HC_Data_Structure;
/**************************************
Local Macros
**************************************/
#define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG))
#define DELTANEXT(p) chainTable[(size_t)(p) & MAXD_MASK]
#define GETNEXT(p) ((p) - (size_t)DELTANEXT(p))
static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
/**************************************
HC Compression
**************************************/
static void LZ4HC_init (LZ4HC_Data_Structure* hc4, const BYTE* start)
{
MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));
MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
hc4->nextToUpdate = 64 KB;
hc4->base = start - 64 KB;
hc4->inputBuffer = start;
hc4->end = start;
hc4->dictBase = start - 64 KB;
hc4->dictLimit = 64 KB;
hc4->lowLimit = 64 KB;
}
/* Update chains up to ip (excluded) */
FORCE_INLINE void LZ4HC_Insert (LZ4HC_Data_Structure* hc4, const BYTE* ip)
{
U16* chainTable = hc4->chainTable;
U32* HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 target = (U32)(ip - base);
U32 idx = hc4->nextToUpdate;
while(idx < target)
{
U32 h = LZ4HC_hashPtr(base+idx);
size_t delta = idx - HashTable[h];
if (delta>MAX_DISTANCE) delta = MAX_DISTANCE;
chainTable[idx & 0xFFFF] = (U16)delta;
HashTable[h] = idx;
idx++;
}
hc4->nextToUpdate = target;
}
FORCE_INLINE int LZ4HC_InsertAndFindBestMatch (LZ4HC_Data_Structure* hc4, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos,
const int maxNbAttempts)
{
U16* const chainTable = hc4->chainTable;
U32* const HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const BYTE* const dictBase = hc4->dictBase;
const U32 dictLimit = hc4->dictLimit;
const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1);
U32 matchIndex;
const BYTE* match;
int nbAttempts=maxNbAttempts;
size_t ml=0;
/* HC4 match finder */
LZ4HC_Insert(hc4, ip);
matchIndex = HashTable[LZ4HC_hashPtr(ip)];
while ((matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(match+ml) == *(ip+ml)
&& (LZ4_read32(match) == LZ4_read32(ip)))
{
size_t mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
if (mlt > ml) { ml = mlt; *matchpos = match; }
}
}
else
{
match = dictBase + matchIndex;
if (LZ4_read32(match) == LZ4_read32(ip))
{
size_t mlt;
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iLimit) vLimit = iLimit;
mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iLimit))
mlt += LZ4_count(ip+mlt, base+dictLimit, iLimit);
if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */
}
}
matchIndex -= chainTable[matchIndex & 0xFFFF];
}
return (int)ml;
}
FORCE_INLINE int LZ4HC_InsertAndGetWiderMatch (
LZ4HC_Data_Structure* hc4,
const BYTE* ip,
const BYTE* iLowLimit,
const BYTE* iHighLimit,
int longest,
const BYTE** matchpos,
const BYTE** startpos,
const int maxNbAttempts)
{
U16* const chainTable = hc4->chainTable;
U32* const HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 dictLimit = hc4->dictLimit;
const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1);
const BYTE* const dictBase = hc4->dictBase;
const BYTE* match;
U32 matchIndex;
int nbAttempts = maxNbAttempts;
int delta = (int)(ip-iLowLimit);
/* First Match */
LZ4HC_Insert(hc4, ip);
matchIndex = HashTable[LZ4HC_hashPtr(ip)];
while ((matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(iLowLimit + longest) == *(match - delta + longest))
if (LZ4_read32(match) == LZ4_read32(ip))
{
const BYTE* startt = ip;
const BYTE* tmpMatch = match;
const BYTE* const matchEnd = ip + MINMATCH + LZ4_count(ip+MINMATCH, match+MINMATCH, iHighLimit);
while ((startt>iLowLimit) && (tmpMatch > iLowLimit) && (startt[-1] == tmpMatch[-1])) {startt--; tmpMatch--;}
if ((matchEnd-startt) > longest)
{
longest = (int)(matchEnd-startt);
*matchpos = tmpMatch;
*startpos = startt;
}
}
}
else
{
match = dictBase + matchIndex;
if (LZ4_read32(match) == LZ4_read32(ip))
{
size_t mlt;
int back=0;
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iHighLimit) vLimit = iHighLimit;
mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iHighLimit))
mlt += LZ4_count(ip+mlt, base+dictLimit, iHighLimit);
while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == match[back-1])) back--;
mlt -= back;
if ((int)mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; }
}
}
matchIndex -= chainTable[matchIndex & 0xFFFF];
}
return longest;
}
typedef enum { noLimit = 0, limitedOutput = 1 } limitedOutput_directive;
#define LZ4HC_DEBUG 0
#if LZ4HC_DEBUG
static unsigned debug = 0;
#endif
FORCE_INLINE int LZ4HC_encodeSequence (
const BYTE** ip,
BYTE** op,
const BYTE** anchor,
int matchLength,
const BYTE* const match,
limitedOutput_directive limitedOutputBuffer,
BYTE* oend)
{
int length;
BYTE* token;
#if LZ4HC_DEBUG
if (debug) printf("literal : %u -- match : %u -- offset : %u\n", (U32)(*ip - *anchor), (U32)matchLength, (U32)(*ip-match));
#endif
/* Encode Literal length */
length = (int)(*ip - *anchor);
token = (*op)++;
if ((limitedOutputBuffer) && ((*op + (length>>8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */
if (length>=(int)RUN_MASK) { int len; *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *(*op)++ = 255; *(*op)++ = (BYTE)len; }
else *token = (BYTE)(length<<ML_BITS);
/* Copy Literals */
LZ4_wildCopy(*op, *anchor, (*op) + length);
*op += length;
/* Encode Offset */
LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2;
/* Encode MatchLength */
length = (int)(matchLength-MINMATCH);
if ((limitedOutputBuffer) && (*op + (length>>8) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */
if (length>=(int)ML_MASK) { *token+=ML_MASK; length-=ML_MASK; for(; length > 509 ; length-=510) { *(*op)++ = 255; *(*op)++ = 255; } if (length > 254) { length-=255; *(*op)++ = 255; } *(*op)++ = (BYTE)length; }
else *token += (BYTE)(length);
/* Prepare next loop */
*ip += matchLength;
*anchor = *ip;
return 0;
}
static int LZ4HC_compress_generic (
void* ctxvoid,
const char* source,
char* dest,
int inputSize,
int maxOutputSize,
int compressionLevel,
limitedOutput_directive limit
)
{
LZ4HC_Data_Structure* ctx = (LZ4HC_Data_Structure*) ctxvoid;
const BYTE* ip = (const BYTE*) source;
const BYTE* anchor = ip;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = (iend - LASTLITERALS);
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + maxOutputSize;
unsigned maxNbAttempts;
int ml, ml2, ml3, ml0;
const BYTE* ref=NULL;
const BYTE* start2=NULL;
const BYTE* ref2=NULL;
const BYTE* start3=NULL;
const BYTE* ref3=NULL;
const BYTE* start0;
const BYTE* ref0;
/* init */
if (compressionLevel > g_maxCompressionLevel) compressionLevel = g_maxCompressionLevel;
if (compressionLevel < 1) compressionLevel = LZ4HC_compressionLevel_default;
maxNbAttempts = 1 << (compressionLevel-1);
ctx->end += inputSize;
ip++;
/* Main Loop */
while (ip < mflimit)
{
ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, (&ref), maxNbAttempts);
if (!ml) { ip++; continue; }
/* saved, in case we would skip too much */
start0 = ip;
ref0 = ref;
ml0 = ml;
_Search2:
if (ip+ml < mflimit)
ml2 = LZ4HC_InsertAndGetWiderMatch(ctx, ip + ml - 2, ip + 1, matchlimit, ml, &ref2, &start2, maxNbAttempts);
else ml2 = ml;
if (ml2 == ml) /* No better match */
{
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
continue;
}
if (start0 < ip)
{
if (start2 < ip + ml0) /* empirical */
{
ip = start0;
ref = ref0;
ml = ml0;
}
}
/* Here, start0==ip */
if ((start2 - ip) < 3) /* First Match too small : removed */
{
ml = ml2;
ip = start2;
ref =ref2;
goto _Search2;
}
_Search3:
/*
* Currently we have :
* ml2 > ml1, and
* ip1+3 <= ip2 (usually < ip1+ml1)
*/
if ((start2 - ip) < OPTIMAL_ML)
{
int correction;
int new_ml = ml;
if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;
if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;
correction = new_ml - (int)(start2 - ip);
if (correction > 0)
{
start2 += correction;
ref2 += correction;
ml2 -= correction;
}
}
/* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */
if (start2 + ml2 < mflimit)
ml3 = LZ4HC_InsertAndGetWiderMatch(ctx, start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3, maxNbAttempts);
else ml3 = ml2;
if (ml3 == ml2) /* No better match : 2 sequences to encode */
{
/* ip & ref are known; Now for ml */
if (start2 < ip+ml) ml = (int)(start2 - ip);
/* Now, encode 2 sequences */
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
ip = start2;
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml2, ref2, limit, oend)) return 0;
continue;
}
if (start3 < ip+ml+3) /* Not enough space for match 2 : remove it */
{
if (start3 >= (ip+ml)) /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
{
if (start2 < ip+ml)
{
int correction = (int)(ip+ml - start2);
start2 += correction;
ref2 += correction;
ml2 -= correction;
if (ml2 < MINMATCH)
{
start2 = start3;
ref2 = ref3;
ml2 = ml3;
}
}
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
ip = start3;
ref = ref3;
ml = ml3;
start0 = start2;
ref0 = ref2;
ml0 = ml2;
goto _Search2;
}
start2 = start3;
ref2 = ref3;
ml2 = ml3;
goto _Search3;
}
/*
* OK, now we have 3 ascending matches; let's write at least the first one
* ip & ref are known; Now for ml
*/
if (start2 < ip+ml)
{
if ((start2 - ip) < (int)ML_MASK)
{
int correction;
if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;
if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;
correction = ml - (int)(start2 - ip);
if (correction > 0)
{
start2 += correction;
ref2 += correction;
ml2 -= correction;
}
}
else
{
ml = (int)(start2 - ip);
}
}
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
ip = start2;
ref = ref2;
ml = ml2;
start2 = start3;
ref2 = ref3;
ml2 = ml3;
goto _Search3;
}
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) (((char*)op)-dest);
}
int LZ4_compressHC2(const char* source, char* dest, int inputSize, int compressionLevel)
{
LZ4HC_Data_Structure ctx;
LZ4HC_init(&ctx, (const BYTE*)source);
return LZ4HC_compress_generic (&ctx, source, dest, inputSize, 0, compressionLevel, noLimit);
}
int LZ4_compressHC(const char* source, char* dest, int inputSize) { return LZ4_compressHC2(source, dest, inputSize, 0); }
int LZ4_compressHC2_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)
{
LZ4HC_Data_Structure ctx;
LZ4HC_init(&ctx, (const BYTE*)source);
return LZ4HC_compress_generic (&ctx, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);
}
int LZ4_compressHC_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4_compressHC2_limitedOutput(source, dest, inputSize, maxOutputSize, 0);
}
/*****************************
* Using external allocation
* ***************************/
int LZ4_sizeofStateHC(void) { return sizeof(LZ4HC_Data_Structure); }
int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel)
{
if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
LZ4HC_init ((LZ4HC_Data_Structure*)state, (const BYTE*)source);
return LZ4HC_compress_generic (state, source, dest, inputSize, 0, compressionLevel, noLimit);
}
int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize)
{ return LZ4_compressHC2_withStateHC (state, source, dest, inputSize, 0); }
int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)
{
if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
LZ4HC_init ((LZ4HC_Data_Structure*)state, (const BYTE*)source);
return LZ4HC_compress_generic (state, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);
}
int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)
{ return LZ4_compressHC2_limitedOutput_withStateHC (state, source, dest, inputSize, maxOutputSize, 0); }
/**************************************
* Streaming Functions
* ************************************/
/* allocation */
LZ4_streamHC_t* LZ4_createStreamHC(void) { return (LZ4_streamHC_t*)malloc(sizeof(LZ4_streamHC_t)); }
int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr) { free(LZ4_streamHCPtr); return 0; }
/* initialization */
void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
{
LZ4_STATIC_ASSERT(sizeof(LZ4HC_Data_Structure) <= LZ4_STREAMHCSIZE); /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */
((LZ4HC_Data_Structure*)LZ4_streamHCPtr)->base = NULL;
((LZ4HC_Data_Structure*)LZ4_streamHCPtr)->compressionLevel = (unsigned)compressionLevel;
}
int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize)
{
LZ4HC_Data_Structure* ctxPtr = (LZ4HC_Data_Structure*) LZ4_streamHCPtr;
if (dictSize > 64 KB)
{
dictionary += dictSize - 64 KB;
dictSize = 64 KB;
}
LZ4HC_init (ctxPtr, (const BYTE*)dictionary);
if (dictSize >= 4) LZ4HC_Insert (ctxPtr, (const BYTE*)dictionary +(dictSize-3));
ctxPtr->end = (const BYTE*)dictionary + dictSize;
return dictSize;
}
/* compression */
static void LZ4HC_setExternalDict(LZ4HC_Data_Structure* ctxPtr, const BYTE* newBlock)
{
if (ctxPtr->end >= ctxPtr->base + 4)
LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */
/* Only one memory segment for extDict, so any previous extDict is lost at this stage */
ctxPtr->lowLimit = ctxPtr->dictLimit;
ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);
ctxPtr->dictBase = ctxPtr->base;
ctxPtr->base = newBlock - ctxPtr->dictLimit;
ctxPtr->end = newBlock;
ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */
}
static int LZ4_compressHC_continue_generic (LZ4HC_Data_Structure* ctxPtr,
const char* source, char* dest,
int inputSize, int maxOutputSize, limitedOutput_directive limit)
{
/* auto-init if forgotten */
if (ctxPtr->base == NULL)
LZ4HC_init (ctxPtr, (const BYTE*) source);
/* Check overflow */
if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB)
{
size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit;
if (dictSize > 64 KB) dictSize = 64 KB;
LZ4_loadDictHC((LZ4_streamHC_t*)ctxPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);
}
/* Check if blocks follow each other */
if ((const BYTE*)source != ctxPtr->end) LZ4HC_setExternalDict(ctxPtr, (const BYTE*)source);
/* Check overlapping input/dictionary space */
{
const BYTE* sourceEnd = (const BYTE*) source + inputSize;
const BYTE* dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit;
const BYTE* dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit;
if ((sourceEnd > dictBegin) && ((BYTE*)source < dictEnd))
{
if (sourceEnd > dictEnd) sourceEnd = dictEnd;
ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase);
if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit;
}
}
return LZ4HC_compress_generic (ctxPtr, source, dest, inputSize, maxOutputSize, ctxPtr->compressionLevel, limit);
}
int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize)
{
return LZ4_compressHC_continue_generic ((LZ4HC_Data_Structure*)LZ4_streamHCPtr, source, dest, inputSize, 0, noLimit);
}
int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4_compressHC_continue_generic ((LZ4HC_Data_Structure*)LZ4_streamHCPtr, source, dest, inputSize, maxOutputSize, limitedOutput);
}
/* dictionary saving */
int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)
{
LZ4HC_Data_Structure* streamPtr = (LZ4HC_Data_Structure*)LZ4_streamHCPtr;
int prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit));
if (dictSize > 64 KB) dictSize = 64 KB;
if (dictSize < 4) dictSize = 0;
if (dictSize > prefixSize) dictSize = prefixSize;
memcpy(safeBuffer, streamPtr->end - dictSize, dictSize);
{
U32 endIndex = (U32)(streamPtr->end - streamPtr->base);
streamPtr->end = (const BYTE*)safeBuffer + dictSize;
streamPtr->base = streamPtr->end - endIndex;
streamPtr->dictLimit = endIndex - dictSize;
streamPtr->lowLimit = endIndex - dictSize;
if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit;
}
return dictSize;
}
/***********************************
* Deprecated Functions
***********************************/
int LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; }
int LZ4_resetStreamStateHC(void* state, const char* inputBuffer)
{
if ((((size_t)state) & (sizeof(void*)-1)) != 0) return 1; /* Error : pointer is not aligned for pointer (32 or 64 bits) */
LZ4HC_init((LZ4HC_Data_Structure*)state, (const BYTE*)inputBuffer);
return 0;
}
void* LZ4_createHC (const char* inputBuffer)
{
void* hc4 = ALLOCATOR(1, sizeof(LZ4HC_Data_Structure));
LZ4HC_init ((LZ4HC_Data_Structure*)hc4, (const BYTE*)inputBuffer);
return hc4;
}
int LZ4_freeHC (void* LZ4HC_Data)
{
FREEMEM(LZ4HC_Data);
return (0);
}
/*
int LZ4_compressHC_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, 0, 0, noLimit);
}
int LZ4_compressHC_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, maxOutputSize, 0, limitedOutput);
}
*/
int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, 0, compressionLevel, noLimit);
}
int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);
}
char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
{
LZ4HC_Data_Structure* hc4 = (LZ4HC_Data_Structure*)LZ4HC_Data;
int dictSize = LZ4_saveDictHC((LZ4_streamHC_t*)LZ4HC_Data, (char*)(hc4->inputBuffer), 64 KB);
return (char*)(hc4->inputBuffer + dictSize);
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/lz4hc.h | C/C++ Header | /*
LZ4 HC - High Compression Mode of LZ4
Header File
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
- LZ4 source repository : http://code.google.com/p/lz4/
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
int LZ4_compressHC (const char* source, char* dest, int inputSize);
/*
LZ4_compressHC :
return : the number of bytes in compressed buffer dest
or 0 if compression fails.
note : destination buffer must be already allocated.
To avoid any problem, size it to handle worst cases situations (input data not compressible)
Worst case size evaluation is provided by function LZ4_compressBound() (see "lz4.h")
*/
int LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize);
/*
LZ4_compress_limitedOutput() :
Compress 'inputSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.
If it cannot achieve it, compression will stop, and result of the function will be zero.
This function never writes outside of provided output buffer.
inputSize : Max supported value is 1 GB
maxOutputSize : is maximum allowed size into the destination buffer (which must be already allocated)
return : the number of output bytes written in buffer 'dest'
or 0 if compression fails.
*/
int LZ4_compressHC2 (const char* source, char* dest, int inputSize, int compressionLevel);
int LZ4_compressHC2_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
/*
Same functions as above, but with programmable 'compressionLevel'.
Recommended values are between 4 and 9, although any value between 0 and 16 will work.
'compressionLevel'==0 means use default 'compressionLevel' value.
Values above 16 behave the same as 16.
Equivalent variants exist for all other compression functions below.
*/
/* Note :
Decompression functions are provided within LZ4 source code (see "lz4.h") (BSD license)
*/
/**************************************
Using an external allocation
**************************************/
int LZ4_sizeofStateHC(void);
int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize);
int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel);
int LZ4_compressHC2_limitedOutput_withStateHC(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
/*
These functions are provided should you prefer to allocate memory for compression tables with your own allocation methods.
To know how much memory must be allocated for the compression tables, use :
int LZ4_sizeofStateHC();
Note that tables must be aligned for pointer (32 or 64 bits), otherwise compression will fail (return code 0).
The allocated memory can be provided to the compression functions using 'void* state' parameter.
LZ4_compress_withStateHC() and LZ4_compress_limitedOutput_withStateHC() are equivalent to previously described functions.
They just use the externally allocated memory for state instead of allocating their own (on stack, or on heap).
*/
/**************************************
Experimental Streaming Functions
**************************************/
#define LZ4_STREAMHCSIZE_U64 32774
#define LZ4_STREAMHCSIZE (LZ4_STREAMHCSIZE_U64 * sizeof(unsigned long long))
typedef struct { unsigned long long table[LZ4_STREAMHCSIZE_U64]; } LZ4_streamHC_t;
/*
LZ4_streamHC_t
This structure allows static allocation of LZ4 HC streaming state.
State must then be initialized using LZ4_resetStreamHC() before first use.
Static allocation should only be used with statically linked library.
If you want to use LZ4 as a DLL, please use construction functions below, which are more future-proof.
*/
LZ4_streamHC_t* LZ4_createStreamHC(void);
int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr);
/*
These functions create and release memory for LZ4 HC streaming state.
Newly created states are already initialized.
Existing state space can be re-used anytime using LZ4_resetStreamHC().
If you use LZ4 as a DLL, please use these functions instead of direct struct allocation,
to avoid size mismatch between different versions.
*/
void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel);
int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize);
int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize);
int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int maxDictSize);
/*
These functions compress data in successive blocks of any size, using previous blocks as dictionary.
One key assumption is that each previous block will remain read-accessible while compressing next block.
Before starting compression, state must be properly initialized, using LZ4_resetStreamHC().
A first "fictional block" can then be designated as initial dictionary, using LZ4_loadDictHC() (Optional).
Then, use LZ4_compressHC_continue() or LZ4_compressHC_limitedOutput_continue() to compress each successive block.
They work like usual LZ4_compressHC() or LZ4_compressHC_limitedOutput(), but use previous memory blocks to improve compression.
Previous memory blocks (including initial dictionary when present) must remain accessible and unmodified during compression.
If, for any reason, previous data block can't be preserved in memory during next compression block,
you must save it to a safer memory space,
using LZ4_saveDictHC().
*/
/**************************************
* Deprecated Streaming Functions
* ************************************/
/* Note : these streaming functions follows the older model, and should no longer be used */
void* LZ4_createHC (const char* inputBuffer);
char* LZ4_slideInputBufferHC (void* LZ4HC_Data);
int LZ4_freeHC (void* LZ4HC_Data);
int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel);
int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
int LZ4_sizeofStreamStateHC(void);
int LZ4_resetStreamStateHC(void* state, const char* inputBuffer);
#if defined (__cplusplus)
}
#endif
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/xxhash.c | C | /*
xxHash - Fast Hash algorithm
Copyright (C) 2012-2015, Yann Collet
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- xxHash source repository : http://code.google.com/p/xxhash/
- xxHash source mirror : https://github.com/Cyan4973/xxHash
- public discussion board : https://groups.google.com/forum/#!forum/lz4c
*/
/**************************************
* Tuning parameters
***************************************/
/* Unaligned memory access is automatically enabled for "common" CPU, such as x86.
* For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected.
* If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance.
* You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32).
*/
#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
# define XXH_USE_UNALIGNED_ACCESS 1
#endif
/* XXH_ACCEPT_NULL_INPUT_POINTER :
* If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer.
* When this option is enabled, xxHash output for null input pointers will be the same as a null-length input.
* By default, this option is disabled. To enable it, uncomment below define :
*/
/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */
/* XXH_FORCE_NATIVE_FORMAT :
* By default, xxHash library provides endian-independant Hash values, based on little-endian convention.
* Results are therefore identical for little-endian and big-endian CPU.
* This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.
* Should endian-independance be of no importance for your application, you may set the #define below to 1.
* It will improve speed for Big-endian CPU.
* This option has no impact on Little_Endian CPU.
*/
#define XXH_FORCE_NATIVE_FORMAT 0
/**************************************
* Compiler Specific Options
***************************************/
#ifdef _MSC_VER /* Visual Studio */
# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
# define FORCE_INLINE static __forceinline
#else
# if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
# ifdef __GNUC__
# define FORCE_INLINE static inline __attribute__((always_inline))
# else
# define FORCE_INLINE static inline
# endif
# else
# define FORCE_INLINE static
# endif /* __STDC_VERSION__ */
#endif
/**************************************
* Includes & Memory related functions
***************************************/
#include "xxhash.h"
/* Modify the local functions below should you wish to use some other memory routines */
/* for malloc(), free() */
#include <stdlib.h>
static void* XXH_malloc(size_t s) { return malloc(s); }
static void XXH_free (void* p) { free(p); }
/* for memcpy() */
#include <string.h>
static void* XXH_memcpy(void* dest, const void* src, size_t size)
{
return memcpy(dest,src,size);
}
/**************************************
* Basic Types
***************************************/
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
# include <stdint.h>
typedef uint8_t BYTE;
typedef uint16_t U16;
typedef uint32_t U32;
typedef int32_t S32;
typedef uint64_t U64;
#else
typedef unsigned char BYTE;
typedef unsigned short U16;
typedef unsigned int U32;
typedef signed int S32;
typedef unsigned long long U64;
#endif
#if defined(__GNUC__) && !defined(XXH_USE_UNALIGNED_ACCESS)
# define _PACKED __attribute__ ((packed))
#else
# define _PACKED
#endif
#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)
# ifdef __IBMC__
# pragma pack(1)
# else
# pragma pack(push, 1)
# endif
#endif
typedef struct _U32_S
{
U32 v;
} _PACKED U32_S;
typedef struct _U64_S
{
U64 v;
} _PACKED U64_S;
#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)
# pragma pack(pop)
#endif
#define A32(x) (((U32_S *)(x))->v)
#define A64(x) (((U64_S *)(x))->v)
/*****************************************
* Compiler-specific Functions and Macros
******************************************/
#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */
#if defined(_MSC_VER)
# define XXH_rotl32(x,r) _rotl(x,r)
# define XXH_rotl64(x,r) _rotl64(x,r)
#else
# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))
# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))
#endif
#if defined(_MSC_VER) /* Visual Studio */
# define XXH_swap32 _byteswap_ulong
# define XXH_swap64 _byteswap_uint64
#elif GCC_VERSION >= 403
# define XXH_swap32 __builtin_bswap32
# define XXH_swap64 __builtin_bswap64
#else
static U32 XXH_swap32 (U32 x)
{
return ((x << 24) & 0xff000000 ) |
((x << 8) & 0x00ff0000 ) |
((x >> 8) & 0x0000ff00 ) |
((x >> 24) & 0x000000ff );
}
static U64 XXH_swap64 (U64 x)
{
return ((x << 56) & 0xff00000000000000ULL) |
((x << 40) & 0x00ff000000000000ULL) |
((x << 24) & 0x0000ff0000000000ULL) |
((x << 8) & 0x000000ff00000000ULL) |
((x >> 8) & 0x00000000ff000000ULL) |
((x >> 24) & 0x0000000000ff0000ULL) |
((x >> 40) & 0x000000000000ff00ULL) |
((x >> 56) & 0x00000000000000ffULL);
}
#endif
/**************************************
* Constants
***************************************/
#define PRIME32_1 2654435761U
#define PRIME32_2 2246822519U
#define PRIME32_3 3266489917U
#define PRIME32_4 668265263U
#define PRIME32_5 374761393U
#define PRIME64_1 11400714785074694791ULL
#define PRIME64_2 14029467366897019727ULL
#define PRIME64_3 1609587929392839161ULL
#define PRIME64_4 9650029242287828579ULL
#define PRIME64_5 2870177450012600261ULL
/***************************************
* Architecture Macros
****************************************/
typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;
#ifndef XXH_CPU_LITTLE_ENDIAN /* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example using a compiler switch */
static const int one = 1;
# define XXH_CPU_LITTLE_ENDIAN (*(char*)(&one))
#endif
/**************************************
* Macros
***************************************/
#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(!!(c)) }; } /* use only *after* variable declarations */
/****************************
* Memory reads
*****************************/
typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;
FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
{
if (align==XXH_unaligned)
return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr));
else
return endian==XXH_littleEndian ? *(U32*)ptr : XXH_swap32(*(U32*)ptr);
}
FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)
{
return XXH_readLE32_align(ptr, endian, XXH_unaligned);
}
FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
{
if (align==XXH_unaligned)
return endian==XXH_littleEndian ? A64(ptr) : XXH_swap64(A64(ptr));
else
return endian==XXH_littleEndian ? *(U64*)ptr : XXH_swap64(*(U64*)ptr);
}
FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)
{
return XXH_readLE64_align(ptr, endian, XXH_unaligned);
}
/****************************
* Simple Hash Functions
*****************************/
FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align)
{
const BYTE* p = (const BYTE*)input;
const BYTE* bEnd = p + len;
U32 h32;
#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align)
#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
if (p==NULL)
{
len=0;
bEnd=p=(const BYTE*)(size_t)16;
}
#endif
if (len>=16)
{
const BYTE* const limit = bEnd - 16;
U32 v1 = seed + PRIME32_1 + PRIME32_2;
U32 v2 = seed + PRIME32_2;
U32 v3 = seed + 0;
U32 v4 = seed - PRIME32_1;
do
{
v1 += XXH_get32bits(p) * PRIME32_2;
v1 = XXH_rotl32(v1, 13);
v1 *= PRIME32_1;
p+=4;
v2 += XXH_get32bits(p) * PRIME32_2;
v2 = XXH_rotl32(v2, 13);
v2 *= PRIME32_1;
p+=4;
v3 += XXH_get32bits(p) * PRIME32_2;
v3 = XXH_rotl32(v3, 13);
v3 *= PRIME32_1;
p+=4;
v4 += XXH_get32bits(p) * PRIME32_2;
v4 = XXH_rotl32(v4, 13);
v4 *= PRIME32_1;
p+=4;
}
while (p<=limit);
h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);
}
else
{
h32 = seed + PRIME32_5;
}
h32 += (U32) len;
while (p+4<=bEnd)
{
h32 += XXH_get32bits(p) * PRIME32_3;
h32 = XXH_rotl32(h32, 17) * PRIME32_4 ;
p+=4;
}
while (p<bEnd)
{
h32 += (*p) * PRIME32_5;
h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;
p++;
}
h32 ^= h32 >> 15;
h32 *= PRIME32_2;
h32 ^= h32 >> 13;
h32 *= PRIME32_3;
h32 ^= h32 >> 16;
return h32;
}
unsigned int XXH32 (const void* input, size_t len, unsigned seed)
{
#if 0
/* Simple version, good for code maintenance, but unfortunately slow for small inputs */
XXH32_state_t state;
XXH32_reset(&state, seed);
XXH32_update(&state, input, len);
return XXH32_digest(&state);
#else
XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
# if !defined(XXH_USE_UNALIGNED_ACCESS)
if ((((size_t)input) & 3) == 0) /* Input is aligned, let's leverage the speed advantage */
{
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
else
return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
}
# endif
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
else
return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
#endif
}
FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align)
{
const BYTE* p = (const BYTE*)input;
const BYTE* bEnd = p + len;
U64 h64;
#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align)
#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
if (p==NULL)
{
len=0;
bEnd=p=(const BYTE*)(size_t)32;
}
#endif
if (len>=32)
{
const BYTE* const limit = bEnd - 32;
U64 v1 = seed + PRIME64_1 + PRIME64_2;
U64 v2 = seed + PRIME64_2;
U64 v3 = seed + 0;
U64 v4 = seed - PRIME64_1;
do
{
v1 += XXH_get64bits(p) * PRIME64_2;
p+=8;
v1 = XXH_rotl64(v1, 31);
v1 *= PRIME64_1;
v2 += XXH_get64bits(p) * PRIME64_2;
p+=8;
v2 = XXH_rotl64(v2, 31);
v2 *= PRIME64_1;
v3 += XXH_get64bits(p) * PRIME64_2;
p+=8;
v3 = XXH_rotl64(v3, 31);
v3 *= PRIME64_1;
v4 += XXH_get64bits(p) * PRIME64_2;
p+=8;
v4 = XXH_rotl64(v4, 31);
v4 *= PRIME64_1;
}
while (p<=limit);
h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
v1 *= PRIME64_2;
v1 = XXH_rotl64(v1, 31);
v1 *= PRIME64_1;
h64 ^= v1;
h64 = h64 * PRIME64_1 + PRIME64_4;
v2 *= PRIME64_2;
v2 = XXH_rotl64(v2, 31);
v2 *= PRIME64_1;
h64 ^= v2;
h64 = h64 * PRIME64_1 + PRIME64_4;
v3 *= PRIME64_2;
v3 = XXH_rotl64(v3, 31);
v3 *= PRIME64_1;
h64 ^= v3;
h64 = h64 * PRIME64_1 + PRIME64_4;
v4 *= PRIME64_2;
v4 = XXH_rotl64(v4, 31);
v4 *= PRIME64_1;
h64 ^= v4;
h64 = h64 * PRIME64_1 + PRIME64_4;
}
else
{
h64 = seed + PRIME64_5;
}
h64 += (U64) len;
while (p+8<=bEnd)
{
U64 k1 = XXH_get64bits(p);
k1 *= PRIME64_2;
k1 = XXH_rotl64(k1,31);
k1 *= PRIME64_1;
h64 ^= k1;
h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
p+=8;
}
if (p+4<=bEnd)
{
h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1;
h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
p+=4;
}
while (p<bEnd)
{
h64 ^= (*p) * PRIME64_5;
h64 = XXH_rotl64(h64, 11) * PRIME64_1;
p++;
}
h64 ^= h64 >> 33;
h64 *= PRIME64_2;
h64 ^= h64 >> 29;
h64 *= PRIME64_3;
h64 ^= h64 >> 32;
return h64;
}
unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed)
{
#if 0
/* Simple version, good for code maintenance, but unfortunately slow for small inputs */
XXH64_state_t state;
XXH64_reset(&state, seed);
XXH64_update(&state, input, len);
return XXH64_digest(&state);
#else
XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
# if !defined(XXH_USE_UNALIGNED_ACCESS)
if ((((size_t)input) & 7)==0) /* Input is aligned, let's leverage the speed advantage */
{
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
else
return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
}
# endif
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
else
return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
#endif
}
/****************************************************
* Advanced Hash Functions
****************************************************/
/*** Allocation ***/
typedef struct
{
U64 total_len;
U32 seed;
U32 v1;
U32 v2;
U32 v3;
U32 v4;
U32 mem32[4]; /* defined as U32 for alignment */
U32 memsize;
} XXH_istate32_t;
typedef struct
{
U64 total_len;
U64 seed;
U64 v1;
U64 v2;
U64 v3;
U64 v4;
U64 mem64[4]; /* defined as U64 for alignment */
U32 memsize;
} XXH_istate64_t;
XXH32_state_t* XXH32_createState(void)
{
XXH_STATIC_ASSERT(sizeof(XXH32_state_t) >= sizeof(XXH_istate32_t)); /* A compilation error here means XXH32_state_t is not large enough */
return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));
}
XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)
{
XXH_free(statePtr);
return XXH_OK;
}
XXH64_state_t* XXH64_createState(void)
{
XXH_STATIC_ASSERT(sizeof(XXH64_state_t) >= sizeof(XXH_istate64_t)); /* A compilation error here means XXH64_state_t is not large enough */
return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));
}
XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)
{
XXH_free(statePtr);
return XXH_OK;
}
/*** Hash feed ***/
XXH_errorcode XXH32_reset(XXH32_state_t* state_in, U32 seed)
{
XXH_istate32_t* state = (XXH_istate32_t*) state_in;
state->seed = seed;
state->v1 = seed + PRIME32_1 + PRIME32_2;
state->v2 = seed + PRIME32_2;
state->v3 = seed + 0;
state->v4 = seed - PRIME32_1;
state->total_len = 0;
state->memsize = 0;
return XXH_OK;
}
XXH_errorcode XXH64_reset(XXH64_state_t* state_in, unsigned long long seed)
{
XXH_istate64_t* state = (XXH_istate64_t*) state_in;
state->seed = seed;
state->v1 = seed + PRIME64_1 + PRIME64_2;
state->v2 = seed + PRIME64_2;
state->v3 = seed + 0;
state->v4 = seed - PRIME64_1;
state->total_len = 0;
state->memsize = 0;
return XXH_OK;
}
FORCE_INLINE XXH_errorcode XXH32_update_endian (XXH32_state_t* state_in, const void* input, size_t len, XXH_endianess endian)
{
XXH_istate32_t* state = (XXH_istate32_t *) state_in;
const BYTE* p = (const BYTE*)input;
const BYTE* const bEnd = p + len;
#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
if (input==NULL) return XXH_ERROR;
#endif
state->total_len += len;
if (state->memsize + len < 16) /* fill in tmp buffer */
{
XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len);
state->memsize += (U32)len;
return XXH_OK;
}
if (state->memsize) /* some data left from previous update */
{
XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize);
{
const U32* p32 = state->mem32;
state->v1 += XXH_readLE32(p32, endian) * PRIME32_2;
state->v1 = XXH_rotl32(state->v1, 13);
state->v1 *= PRIME32_1;
p32++;
state->v2 += XXH_readLE32(p32, endian) * PRIME32_2;
state->v2 = XXH_rotl32(state->v2, 13);
state->v2 *= PRIME32_1;
p32++;
state->v3 += XXH_readLE32(p32, endian) * PRIME32_2;
state->v3 = XXH_rotl32(state->v3, 13);
state->v3 *= PRIME32_1;
p32++;
state->v4 += XXH_readLE32(p32, endian) * PRIME32_2;
state->v4 = XXH_rotl32(state->v4, 13);
state->v4 *= PRIME32_1;
p32++;
}
p += 16-state->memsize;
state->memsize = 0;
}
if (p <= bEnd-16)
{
const BYTE* const limit = bEnd - 16;
U32 v1 = state->v1;
U32 v2 = state->v2;
U32 v3 = state->v3;
U32 v4 = state->v4;
do
{
v1 += XXH_readLE32(p, endian) * PRIME32_2;
v1 = XXH_rotl32(v1, 13);
v1 *= PRIME32_1;
p+=4;
v2 += XXH_readLE32(p, endian) * PRIME32_2;
v2 = XXH_rotl32(v2, 13);
v2 *= PRIME32_1;
p+=4;
v3 += XXH_readLE32(p, endian) * PRIME32_2;
v3 = XXH_rotl32(v3, 13);
v3 *= PRIME32_1;
p+=4;
v4 += XXH_readLE32(p, endian) * PRIME32_2;
v4 = XXH_rotl32(v4, 13);
v4 *= PRIME32_1;
p+=4;
}
while (p<=limit);
state->v1 = v1;
state->v2 = v2;
state->v3 = v3;
state->v4 = v4;
}
if (p < bEnd)
{
XXH_memcpy(state->mem32, p, bEnd-p);
state->memsize = (int)(bEnd-p);
}
return XXH_OK;
}
XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)
{
XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
else
return XXH32_update_endian(state_in, input, len, XXH_bigEndian);
}
FORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state_in, XXH_endianess endian)
{
XXH_istate32_t* state = (XXH_istate32_t*) state_in;
const BYTE * p = (const BYTE*)state->mem32;
BYTE* bEnd = (BYTE*)(state->mem32) + state->memsize;
U32 h32;
if (state->total_len >= 16)
{
h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18);
}
else
{
h32 = state->seed + PRIME32_5;
}
h32 += (U32) state->total_len;
while (p+4<=bEnd)
{
h32 += XXH_readLE32(p, endian) * PRIME32_3;
h32 = XXH_rotl32(h32, 17) * PRIME32_4;
p+=4;
}
while (p<bEnd)
{
h32 += (*p) * PRIME32_5;
h32 = XXH_rotl32(h32, 11) * PRIME32_1;
p++;
}
h32 ^= h32 >> 15;
h32 *= PRIME32_2;
h32 ^= h32 >> 13;
h32 *= PRIME32_3;
h32 ^= h32 >> 16;
return h32;
}
U32 XXH32_digest (const XXH32_state_t* state_in)
{
XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH32_digest_endian(state_in, XXH_littleEndian);
else
return XXH32_digest_endian(state_in, XXH_bigEndian);
}
FORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state_in, const void* input, size_t len, XXH_endianess endian)
{
XXH_istate64_t * state = (XXH_istate64_t *) state_in;
const BYTE* p = (const BYTE*)input;
const BYTE* const bEnd = p + len;
#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
if (input==NULL) return XXH_ERROR;
#endif
state->total_len += len;
if (state->memsize + len < 32) /* fill in tmp buffer */
{
XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len);
state->memsize += (U32)len;
return XXH_OK;
}
if (state->memsize) /* some data left from previous update */
{
XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize);
{
const U64* p64 = state->mem64;
state->v1 += XXH_readLE64(p64, endian) * PRIME64_2;
state->v1 = XXH_rotl64(state->v1, 31);
state->v1 *= PRIME64_1;
p64++;
state->v2 += XXH_readLE64(p64, endian) * PRIME64_2;
state->v2 = XXH_rotl64(state->v2, 31);
state->v2 *= PRIME64_1;
p64++;
state->v3 += XXH_readLE64(p64, endian) * PRIME64_2;
state->v3 = XXH_rotl64(state->v3, 31);
state->v3 *= PRIME64_1;
p64++;
state->v4 += XXH_readLE64(p64, endian) * PRIME64_2;
state->v4 = XXH_rotl64(state->v4, 31);
state->v4 *= PRIME64_1;
p64++;
}
p += 32-state->memsize;
state->memsize = 0;
}
if (p+32 <= bEnd)
{
const BYTE* const limit = bEnd - 32;
U64 v1 = state->v1;
U64 v2 = state->v2;
U64 v3 = state->v3;
U64 v4 = state->v4;
do
{
v1 += XXH_readLE64(p, endian) * PRIME64_2;
v1 = XXH_rotl64(v1, 31);
v1 *= PRIME64_1;
p+=8;
v2 += XXH_readLE64(p, endian) * PRIME64_2;
v2 = XXH_rotl64(v2, 31);
v2 *= PRIME64_1;
p+=8;
v3 += XXH_readLE64(p, endian) * PRIME64_2;
v3 = XXH_rotl64(v3, 31);
v3 *= PRIME64_1;
p+=8;
v4 += XXH_readLE64(p, endian) * PRIME64_2;
v4 = XXH_rotl64(v4, 31);
v4 *= PRIME64_1;
p+=8;
}
while (p<=limit);
state->v1 = v1;
state->v2 = v2;
state->v3 = v3;
state->v4 = v4;
}
if (p < bEnd)
{
XXH_memcpy(state->mem64, p, bEnd-p);
state->memsize = (int)(bEnd-p);
}
return XXH_OK;
}
XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)
{
XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH64_update_endian(state_in, input, len, XXH_littleEndian);
else
return XXH64_update_endian(state_in, input, len, XXH_bigEndian);
}
FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state_in, XXH_endianess endian)
{
XXH_istate64_t * state = (XXH_istate64_t *) state_in;
const BYTE * p = (const BYTE*)state->mem64;
BYTE* bEnd = (BYTE*)state->mem64 + state->memsize;
U64 h64;
if (state->total_len >= 32)
{
U64 v1 = state->v1;
U64 v2 = state->v2;
U64 v3 = state->v3;
U64 v4 = state->v4;
h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
v1 *= PRIME64_2;
v1 = XXH_rotl64(v1, 31);
v1 *= PRIME64_1;
h64 ^= v1;
h64 = h64*PRIME64_1 + PRIME64_4;
v2 *= PRIME64_2;
v2 = XXH_rotl64(v2, 31);
v2 *= PRIME64_1;
h64 ^= v2;
h64 = h64*PRIME64_1 + PRIME64_4;
v3 *= PRIME64_2;
v3 = XXH_rotl64(v3, 31);
v3 *= PRIME64_1;
h64 ^= v3;
h64 = h64*PRIME64_1 + PRIME64_4;
v4 *= PRIME64_2;
v4 = XXH_rotl64(v4, 31);
v4 *= PRIME64_1;
h64 ^= v4;
h64 = h64*PRIME64_1 + PRIME64_4;
}
else
{
h64 = state->seed + PRIME64_5;
}
h64 += (U64) state->total_len;
while (p+8<=bEnd)
{
U64 k1 = XXH_readLE64(p, endian);
k1 *= PRIME64_2;
k1 = XXH_rotl64(k1,31);
k1 *= PRIME64_1;
h64 ^= k1;
h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
p+=8;
}
if (p+4<=bEnd)
{
h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1;
h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
p+=4;
}
while (p<bEnd)
{
h64 ^= (*p) * PRIME64_5;
h64 = XXH_rotl64(h64, 11) * PRIME64_1;
p++;
}
h64 ^= h64 >> 33;
h64 *= PRIME64_2;
h64 ^= h64 >> 29;
h64 *= PRIME64_3;
h64 ^= h64 >> 32;
return h64;
}
unsigned long long XXH64_digest (const XXH64_state_t* state_in)
{
XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
return XXH64_digest_endian(state_in, XXH_littleEndian);
else
return XXH64_digest_endian(state_in, XXH_bigEndian);
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/lz4/xxhash.h | C/C++ Header | /*
xxHash - Extremely Fast Hash algorithm
Header File
Copyright (C) 2012-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- xxHash source repository : http://code.google.com/p/xxhash/
*/
/* Notice extracted from xxHash homepage :
xxHash is an extremely fast Hash algorithm, running at RAM speed limits.
It also successfully passes all tests from the SMHasher suite.
Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)
Name Speed Q.Score Author
xxHash 5.4 GB/s 10
CrapWow 3.2 GB/s 2 Andrew
MumurHash 3a 2.7 GB/s 10 Austin Appleby
SpookyHash 2.0 GB/s 10 Bob Jenkins
SBox 1.4 GB/s 9 Bret Mulvey
Lookup3 1.2 GB/s 9 Bob Jenkins
SuperFastHash 1.2 GB/s 1 Paul Hsieh
CityHash64 1.05 GB/s 10 Pike & Alakuijala
FNV 0.55 GB/s 5 Fowler, Noll, Vo
CRC32 0.43 GB/s 9
MD5-32 0.33 GB/s 10 Ronald L. Rivest
SHA1-32 0.28 GB/s 10
Q.Score is a measure of quality of the hash function.
It depends on successfully passing SMHasher test set.
10 is a perfect score.
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
/*****************************
Includes
*****************************/
#include <stddef.h> /* size_t */
/*****************************
Type
*****************************/
typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;
/*****************************
Simple Hash Functions
*****************************/
unsigned int XXH32 (const void* input, size_t length, unsigned seed);
unsigned long long XXH64 (const void* input, size_t length, unsigned long long seed);
/*
XXH32() :
Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input".
The memory between input & input+length must be valid (allocated and read-accessible).
"seed" can be used to alter the result predictably.
This function successfully passes all SMHasher tests.
Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s
XXH64() :
Calculate the 64-bits hash of sequence of length "len" stored at memory address "input".
*/
/*****************************
Advanced Hash Functions
*****************************/
typedef struct { long long ll[ 6]; } XXH32_state_t;
typedef struct { long long ll[11]; } XXH64_state_t;
/*
These structures allow static allocation of XXH states.
States must then be initialized using XXHnn_reset() before first use.
If you prefer dynamic allocation, please refer to functions below.
*/
XXH32_state_t* XXH32_createState(void);
XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr);
XXH64_state_t* XXH64_createState(void);
XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr);
/*
These functions create and release memory for XXH state.
States must then be initialized using XXHnn_reset() before first use.
*/
XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned seed);
XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
unsigned int XXH32_digest (const XXH32_state_t* statePtr);
XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed);
XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);
unsigned long long XXH64_digest (const XXH64_state_t* statePtr);
/*
These functions calculate the xxHash of an input provided in multiple smaller packets,
as opposed to an input provided as a single block.
XXH state space must first be allocated, using either static or dynamic method provided above.
Start a new hash by initializing state with a seed, using XXHnn_reset().
Then, feed the hash state by calling XXHnn_update() as many times as necessary.
Obviously, input must be valid, meaning allocated and read accessible.
The function returns an error code, with 0 meaning OK, and any other value meaning there is an error.
Finally, you can produce a hash anytime, by using XXHnn_digest().
This function returns the final nn-bits hash.
You can nonetheless continue feeding the hash state with more input,
and therefore get some new hashes, by calling again XXHnn_digest().
When you are done, don't forget to free XXH state space, using typically XXHnn_freeState().
*/
#if defined (__cplusplus)
}
#endif
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/pack/pack.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "pack.h"
#include "../lz4/lz4.h"
#include "../crc32/crc32.h"
#include <unone.h>
#include <time.h>
/*******************************/
//BundleHeader
//...[Crypted]
//......[Compressed]
//.........BundleScript
//.........BundleRecord
//.........BundleRecord
//.....................
//......[Compressed]
//...[Crypted]
/*******************************/
#define BUNDLE_MAGIC 'BUDE'
#define BUNDLE_XORKEY 0x99
#pragma pack(push,1)
struct BundleHeader {
uint32_t magic; //'BUDE'
uint32_t timestamp; //timestamp
uint64_t orisize; //original size
uint64_t cpsize; //compressed size
uint32_t crc32; //crc32
uint32_t recordcnt; //record count
uint16_t dirname[MAX_PATH]; //root dir name
};
struct BundleScript {
uint32_t len;
uint16_t buf[1];
};
struct BundleRecord {
uint64_t size;
uint32_t crc32;
uint16_t name[MAX_PATH];
uint8_t data[1];
};
#pragma pack(pop)
BOOL BundleWriteFile(HANDLE fd, LPCVOID buf, DWORD buflen, LPDWORD writelen, LPOVERLAPPED overlapped)
{
DWORD i = buflen;
while (i--) {
((PBYTE)buf)[i] ^= BUNDLE_XORKEY;
}
BOOL result = WriteFile(fd, buf, buflen, writelen, overlapped);
i = buflen;
while (i--) {
((PBYTE)buf)[i] ^= BUNDLE_XORKEY;
}
return result;
}
BOOL BundleReadFile(HANDLE fd, LPVOID buf, DWORD buflen, LPDWORD readlen, LPOVERLAPPED overlapped)
{
if (ReadFile(fd, buf, buflen, readlen, overlapped)) {
DWORD i = *readlen;
while (i--) {
((PBYTE)buf)[i] ^= BUNDLE_XORKEY;
}
}
return FALSE;
}
BOOL BundleReadMemory(const char* data, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, BOOL reset = FALSE)
{
static DWORD offset = 0;
if (reset)
offset = 0;
DWORD i = nNumberOfBytesToRead;
while (i--) {
((PBYTE)lpBuffer)[i] = data[offset + i] ^ BUNDLE_XORKEY;
}
offset += nNumberOfBytesToRead;
return TRUE;
}
BOOL BundleCrypt(std::string &data)
{
for (auto& c : data) {
c ^= BUNDLE_XORKEY;
}
return TRUE;
}
BundleError BundleVerify(BundleHeader *bhdr)
{
if (bhdr->magic != BUNDLE_MAGIC) {
return BERR_INVALID_FILEMAGIC;
}
if (bhdr->cpsize < 0 || bhdr->orisize < 0) {
return BERR_INVALID_HEADER;
}
if (bhdr->recordcnt < 0) {
return BERR_INVALID_RECORDCOUNT;
}
return BERR_OK;
}
BundleError BundlePack(const std::wstring &dirname, std::vector<std::wstring> &files,
std::vector<std::wstring> &names, std::wstring script, std::string &bdata)
{
BundleError err = BERR_OK;
int recordcount = 0;
std::string buf;
BundleScript s = {0};
s.len = script.size();
buf.append((char*)&s, sizeof(BundleScript) - 2);
buf.append((char*)script.c_str(), script.size() * 2);
for (size_t i = 0; i < files.size(); i++) {
std::string data;
std::wstring path = files[i];
std::wstring name = names[i];
if (!UNONE::FsReadFileDataW(path, data)) {
err = BERR_FAIL_READ;
break;
}
BundleRecord record = { 0 };
if (data.size() > 0) {
record.crc32 = crc32(data.data(), data.size());
}
wcsncpy_s((wchar_t*)record.name, MAX_PATH, name.c_str(), MAX_PATH - 1);
record.size = data.size();
buf.append((char*)&record, sizeof(BundleRecord) - 1);
buf.append(data);
}
if (err != BERR_OK) {
return err;
}
int maxsize = LZ4_compressBound(buf.size());
std::string cpdata;
cpdata.resize(maxsize);
int cpsize = LZ4_compress(buf.data(), (char *)cpdata.data(), buf.size());
cpdata.resize(cpsize);
BundleCrypt(cpdata);
BundleHeader bhdr = { 0 };
bhdr.magic = BUNDLE_MAGIC;
bhdr.crc32 = crc32((unsigned char*)buf.data(), buf.size());
bhdr.cpsize = cpsize;
bhdr.orisize = buf.size();
bhdr.recordcnt = files.size();
bhdr.timestamp = (uint32_t)time(0);
wcsncpy_s((wchar_t*)bhdr.dirname, MAX_PATH, dirname.c_str(), MAX_PATH - 1);
std::string bstr((char*)&bhdr, sizeof(BundleHeader));
BundleCrypt(bstr);
bdata.append(bstr);
bdata.append(cpdata);
return BERR_OK;
}
BundleError BundleUnpack(const std::wstring &outdir, const char *bdata, std::wstring &script, std::wstring &dirname)
{
BundleError err = BERR_OK;
BundleHeader bhdr = { 0 };
if (!BundleReadMemory(bdata, &bhdr, sizeof(bhdr), TRUE)) {
return BERR_FAIL_READ;
}
err = BundleVerify(&bhdr);
if (err != BERR_OK) {
return err;
}
dirname = (wchar_t*)bhdr.dirname;
uint64_t oribuflen = bhdr.orisize + 64;
uint64_t cpbuflen = bhdr.cpsize;
std::string cpdata, oridata;
cpdata.resize((unsigned int)cpbuflen);
oridata.resize((unsigned int)oribuflen);
BundleReadMemory(bdata, (LPVOID)cpdata.data(), (DWORD)bhdr.cpsize);
int size = LZ4_decompress_safe(cpdata.data(), (char*)oridata.data(), (int)cpbuflen, (int)oribuflen);
if (size == 0) {
return BERR_FAIL_DECOMPRESSED;
}
uint32_t hash = crc32(oridata.data(), size);
if (hash != bhdr.crc32) {
return BERR_INVALID_HEADER;
}
BundleScript *sptr = (BundleScript*)oridata.data();
script.assign((wchar_t*)sptr->buf, sptr->len);
BundleRecord *rptr = (BundleRecord*)((char*)sptr + sizeof(BundleScript) - 2 + sptr->len*2);
for (int i = 0; i < (int)bhdr.recordcnt; i++) {
if (rptr->size != 0) {
if (crc32(rptr->data, (uint32_t)rptr->size) != rptr->crc32) {
err = BERR_INVALID_RECORDCRC32;
break;
}
}
std::wstring&& path = UNONE::FsPathComposeW(outdir, (wchar_t*)rptr->name);
std::wstring&& dir = UNONE::FsPathToDirW(path);
if (!UNONE::FsCreateDirW(dir)) {
err = BERR_FAIL_CREATEDIR;
break;
}
HANDLE fd = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (fd == INVALID_HANDLE_VALUE) {
err = BERR_FAIL_CREATEFILE;
break;
}
if (rptr->size != 0) {
DWORD wlen;
if (!WriteFile(fd, rptr->data, (DWORD)rptr->size, &wlen, NULL)) {
err = BERR_FAIL_WRITE;
CloseHandle(fd);
break;
}
}
rptr = (BundleRecord*)(((uint8_t*)rptr) + rptr->size - 1 + sizeof(BundleRecord));
CloseHandle(fd);
}
return err;
}
BundleError BundleGetDirName(const char *bdata, std::wstring &dirname)
{
BundleError err = BERR_OK;
BundleHeader bhdr = { 0 };
DWORD readlen = 0;
if (!BundleReadMemory(bdata, &bhdr, sizeof(bhdr), TRUE)) {
return BERR_FAIL_READ;
}
err = BundleVerify(&bhdr);
if (err != BERR_OK) {
return err;
}
dirname = (wchar_t*)bhdr.dirname;
return err;
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/bundler/pack/pack.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <Windows.h>
#include <stdint.h>
#include <string>
#include <vector>
#define IDX_BUDE 108
#define IDS_BUDE L"IDR_BUDE"
enum BundleError {
BERR_OK = 0,
BERR_INVALID_FILEMAGIC,
BERR_INVALID_HEADER,
BERR_INVALID_COMPRESS,
BERR_INVALID_SCRIPTCOUNT,
BERR_INVALID_RECORDCOUNT,
BERR_INVALID_RECORDSIZE,
BERR_INVALID_RECORDCRC32,
BERR_FAIL_COMPRESSED,
BERR_FAIL_DECOMPRESSED,
BERR_FAIL_OPEN,
BERR_FAIL_READ,
BERR_FAIL_WRITE,
BERR_FAIL_CREATEDIR,
BERR_FAIL_CREATEFILE,
};
BundleError BundlePack(const std::wstring &dirname, std::vector<std::wstring> &files,
std::vector<std::wstring> &names, std::wstring script, std::string &bdata);
BundleError BundleUnpack(const std::wstring &outdir, const char *bdata, std::wstring &script, std::wstring &dirname);
BundleError BundleGetDirName(const char *bdata, std::wstring &dirname); | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/cmds/cmds.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include "../common/common.h"
enum {
ECMD_PARAM_INVALID,
ECMD_NOSUCH_CMD,
};
class Cmds : public QTextBrowser {
Q_OBJECT
public:
Cmds (QTextBrowser *parent);
~Cmds ();
public:
Q_INVOKABLE void CmdHelp(QString cmd, QStringList argv);
Q_INVOKABLE void CmdCls(QString cmd, QStringList argv);
Q_INVOKABLE void CmdHistory(QString cmd, QStringList argv);
Q_INVOKABLE void CmdTimeStamp(QString cmd, QStringList argv);
Q_INVOKABLE void CmdErrorShow(QString cmd, QStringList argv);
Q_INVOKABLE void CmdFormats(QString cmd, QStringList argv);
Q_INVOKABLE void CmdExit(QString cmd, QStringList argv);
Q_INVOKABLE void CmdRestart(QString cmd, QStringList argv);
Q_INVOKABLE void CmdCmd(QString cmd, QStringList argv);
Q_INVOKABLE void CmdStart(QString cmd, QStringList argv);
Q_INVOKABLE void CmdMsg(QString cmd, QStringList argv);
Q_INVOKABLE void CmdWndInfo(QString cmd, QStringList argv);
Q_INVOKABLE void CmdProcessInfo(QString cmd, QStringList argv);
Q_INVOKABLE void CmdProcessTree(QString cmd, QStringList argv);
Q_INVOKABLE void CmdMemoryEditor(QString cmd, QStringList argv);
Q_INVOKABLE void CmdFileEditor(QString cmd, QStringList argv);
QString CmdGetLast();
QString CmdGetNext();
void CmdException(QString cmd, int type);
void CmdErrorOutput(const std::wstring &err);
void CmdOutput(const char* format, ...);
void CmdOutput(const wchar_t* format, ...);
void CmdDispatcher(const std::wstring &cmdline);
size_t cmd_cursor_;
QStringList cmd_history_;
QTextBrowser *cmd_window_;
}; | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/cmds/constants/constants.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "constants.h"
#include "../../common/common.h"
#include <arkdrv-api/api-object/api-object.h>
//Win7
std::map<int, std::wstring> ObjectTypeTable;// = { { 2,"Type" },{ 3,"Directory" },{ 4,"SymbolicLink" },{ 5,"Token" },{ 6,"Job" },{ 7,"Process" },{ 8,"Thread" },{ 9,"UserApcReserve" },{ 10,"IoCompletionReserve" },{ 11,"DebugObject" },{ 12,"Event" },{ 13,"EventPair" },{ 14,"Mutant" },{ 15,"Callback" },{ 16,"Semaphore" },{ 17,"Timer" },{ 18,"Profile" },{ 19,"KeyedEvent" },{ 20,"WindowStation" },{ 21,"Desktop" },{ 22,"TpWorkerFactory" },{ 23,"Adapter" },{ 24,"Controller" },{ 25,"Device" },{ 26,"Driver" },{ 27,"IoCompletion" },{ 28,"File" },{ 29,"TmTm" },{ 30,"TmTx" },{ 31,"TmRm" },{ 32,"TmEn" },{ 33,"Section" },{ 34,"Session" },{ 35,"Key" },{ 36,"ALPC Port" },{ 37,"PowerRequest" },{ 38,"WmiGuid" },{ 39,"EtwRegistration" },{ 40,"EtwConsumer" },{ 41,"FilterConnectionPort" },{ 42,"FilterCommunicationPort" },{ 43,"PcwObject" } };
char *MessageRawString = "WM_NULL=0x0000,WM_CREATE=0x0001,WM_DESTROY=0x0002,WM_MOVE=0x0003,WM_SIZE=0x0005,WM_ACTIVATE=0x0006,WM_SETFOCUS=0x0007,WM_KILLFOCUS=0x0008,WM_ENABLE=0x000A,WM_SETREDRAW=0x000B,WM_SETTEXT=0x000C,WM_GETTEXT=0x000D,WM_GETTEXTLENGTH=0x000E,WM_PAINT=0x000F,WM_CLOSE=0x0010,WM_QUERYENDSESSION=0x0011,WM_QUIT=0x0012,WM_QUERYOPEN=0x0013,WM_ERASEBKGND=0x0014,WM_SYSCOLORCHANGE=0x0015,WM_ENDSESSION=0x0016,WM_SHOWWINDOW=0x0018,WM_WININICHANGE=0x001A,WM_SETTINGCHANGE=0x001A,WM_DEVMODECHANGE=0x001B,WM_ACTIVATEAPP=0x001C,WM_FONTCHANGE=0x001D,WM_TIMECHANGE=0x001E,WM_CANCELMODE=0x001F,WM_SETCURSOR=0x0020,WM_MOUSEACTIVATE=0x0021,WM_CHILDACTIVATE=0x0022,WM_QUEUESYNC=0x0023,WM_GETMINMAXINFO=0x0024,WM_PAINTICON=0x0026,WM_ICONERASEBKGND=0x0027,WM_NEXTDLGCTL=0x0028,WM_SPOOLERSTATUS=0x002A,WM_DRAWITEM=0x002B,WM_MEASUREITEM=0x002C,WM_DELETEITEM=0x002D,WM_VKEYTOITEM=0x002E,WM_CHARTOITEM=0x002F,WM_SETFONT=0x0030,WM_GETFONT=0x0031,WM_SETHOTKEY=0x0032,WM_GETHOTKEY=0x0033,WM_QUERYDRAGICON=0x0037,WM_COMPAREITEM=0x0039,WM_GETOBJECT=0x003D,WM_COMPACTING=0x0041,WM_COMMNOTIFY=0x0044,WM_WINDOWPOSCHANGING=0x0046,WM_WINDOWPOSCHANGED=0x0047,WM_POWER=0x0048,WM_COPYDATA=0x004A,WM_CANCELJOURNAL=0x004B,WM_NOTIFY=0x004E,WM_INPUTLANGCHANGEREQUEST=0x0050,WM_INPUTLANGCHANGE=0x0051,WM_TCARD=0x0052,WM_HELP=0x0053,WM_USERCHANGED=0x0054,WM_NOTIFYFORMAT=0x0055,WM_CONTEXTMENU=0x007B,WM_STYLECHANGING=0x007C,WM_STYLECHANGED=0x007D,WM_DISPLAYCHANGE=0x007E,WM_GETICON=0x007F,WM_SETICON=0x0080,WM_NCCREATE=0x0081,WM_NCDESTROY=0x0082,WM_NCCALCSIZE=0x0083,WM_NCHITTEST=0x0084,WM_NCPAINT=0x0085,WM_NCACTIVATE=0x0086,WM_GETDLGCODE=0x0087,WM_SYNCPAINT=0x0088,WM_NCMOUSEMOVE=0x00A0,WM_NCLBUTTONDOWN=0x00A1,WM_NCLBUTTONUP=0x00A2,WM_NCLBUTTONDBLCLK=0x00A3,WM_NCRBUTTONDOWN=0x00A4,WM_NCRBUTTONUP=0x00A5,WM_NCRBUTTONDBLCLK=0x00A6,WM_NCMBUTTONDOWN=0x00A7,WM_NCMBUTTONUP=0x00A8,WM_NCMBUTTONDBLCLK=0x00A9,WM_KEYDOWN=0x0100,WM_KEYUP=0x0101,WM_CHAR=0x0102,WM_DEADCHAR=0x0103,WM_SYSKEYDOWN=0x0104,WM_SYSKEYUP=0x0105,WM_SYSCHAR=0x0106,WM_SYSDEADCHAR=0x0107,WM_KEYLAST=0x0108,WM_IME_STARTCOMPOSITION=0x010D,WM_IME_ENDCOMPOSITION=0x010E,WM_IME_COMPOSITION=0x010F,WM_IME_KEYLAST=0x010F,WM_INITDIALOG=0x0110,WM_COMMAND=0x0111,WM_SYSCOMMAND=0x0112,WM_TIMER=0x0113,WM_HSCROLL=0x0114,WM_VSCROLL=0x0115,WM_INITMENU=0x0116,WM_INITMENUPOPUP=0x0117,WM_MENUSELECT=0x011F,WM_MENUCHAR=0x0120,WM_ENTERIDLE=0x0121,WM_MENURBUTTONUP=0x0122,WM_MENUDRAG=0x0123,WM_MENUGETOBJECT=0x0124,WM_UNINITMENUPOPUP=0x0125,WM_MENUCOMMAND=0x0126,WM_CTLCOLORMSGBOX=0x0132,WM_CTLCOLOREDIT=0x0133,WM_CTLCOLORLISTBOX=0x0134,WM_CTLCOLORBTN=0x0135,WM_CTLCOLORDLG=0x0136,WM_CTLCOLORSCROLLBAR=0x0137,WM_CTLCOLORSTATIC=0x0138,WM_MOUSEMOVE=0x0200,WM_LBUTTONDOWN=0x0201,WM_LBUTTONUP=0x0202,WM_LBUTTONDBLCLK=0x0203,WM_RBUTTONDOWN=0x0204,WM_RBUTTONUP=0x0205,WM_RBUTTONDBLCLK=0x0206,WM_MBUTTONDOWN=0x0207,WM_MBUTTONUP=0x0208,WM_MBUTTONDBLCLK=0x0209,WM_MOUSEWHEEL=0x020A,WM_PARENTNOTIFY=0x0210,WM_ENTERMENULOOP=0x0211,WM_EXITMENULOOP=0x0212,WM_NEXTMENU=0x0213,WM_SIZING=0x0214,WM_CAPTURECHANGED=0x0215,WM_MOVING=0x0216,WM_DEVICECHANGE=0x0219,WM_MDICREATE=0x0220,WM_MDIDESTROY=0x0221,WM_MDIACTIVATE=0x0222,WM_MDIRESTORE=0x0223,WM_MDINEXT=0x0224,WM_MDIMAXIMIZE=0x0225,WM_MDITILE=0x0226,WM_MDICASCADE=0x0227,WM_MDIICONARRANGE=0x0228,WM_MDIGETACTIVE=0x0229,WM_MDISETMENU=0x0230,WM_ENTERSIZEMOVE=0x0231,WM_EXITSIZEMOVE=0x0232,WM_DROPFILES=0x0233,WM_MDIREFRESHMENU=0x0234,WM_IME_SETCONTEXT=0x0281,WM_IME_NOTIFY=0x0282,WM_IME_CONTROL=0x0283,WM_IME_COMPOSITIONFULL=0x0284,WM_IME_SELECT=0x0285,WM_IME_CHAR=0x0286,WM_IME_REQUEST=0x0288,WM_IME_KEYDOWN=0x0290,WM_IME_KEYUP=0x0291,WM_MOUSEHOVER=0x02A1,WM_MOUSELEAVE=0x02A3,WM_CUT=0x0300,WM_COPY=0x0301,WM_PASTE=0x0302,WM_CLEAR=0x0303,WM_UNDO=0x0304,WM_RENDERFORMAT=0x0305,WM_RENDERALLFORMATS=0x0306,WM_DESTROYCLIPBOARD=0x0307,WM_DRAWCLIPBOARD=0x0308,WM_PAINTCLIPBOARD=0x0309,WM_VSCROLLCLIPBOARD=0x030A,WM_SIZECLIPBOARD=0x030B,WM_ASKCBFORMATNAME=0x030C,WM_CHANGECBCHAIN=0x030D,WM_HSCROLLCLIPBOARD=0x030E,WM_QUERYNEWPALETTE=0x030F,WM_PALETTEISCHANGING=0x0310,WM_PALETTECHANGED=0x0311,WM_HOTKEY=0x0312,WM_PRINT=0x0317,WM_PRINTCLIENT=0x0318,WM_HANDHELDFIRST=0x0358,WM_HANDHELDLAST=0x035F,WM_AFXFIRST=0x0360,WM_AFXLAST=0x037F,WM_PENWINFIRST=0x0380,WM_PENWINLAST=0x038F,WM_APP=0x8000,WM_USER=0x0400";
std::map<int, std::string> MessageMapTable;
// Dynamic retrieve ObjectIndex ID
void InitObjectTypeTable()
{
if (!ObjectTypeTable.empty()) return;
std::vector<ARK_OBJECT_TYPE_ITEM> items;
ArkDrvApi::Object::ObjectTypeEnum(items);
for (auto &item : items) {
ObjectTypeTable[item.type_index] = item.type_name;
}
return;
ObjectTypeTable[2] = L"Type";
ObjectTypeTable[3] = L"Directory";
ObjectTypeTable[4] = L"SymbolicLink";
ObjectTypeTable[5] = L"Token";
ObjectTypeTable[6] = L"Job";
ObjectTypeTable[7] = L"Process";
ObjectTypeTable[8] = L"Thread";
auto file = CreateFileW(UNONE::PsGetProcessPathW().c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
auto iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 0);
auto desktop = GetThreadDesktop(GetCurrentThreadId());
auto event = CreateEventW(NULL, FALSE, FALSE, NULL);
auto mutant = CreateMutexW(NULL, FALSE, NULL);
auto semaphore = CreateSemaphoreW(NULL, 1, 1, NULL);
auto section = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READONLY, 0, 0x1000, NULL);
auto station = GetProcessWindowStation();
HKEY key;
RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SYSTEM", &key);
typedef NTSTATUS (NTAPI *__NtCreateKeyedEvent)(
OUT PHANDLE KeyedEventHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
IN ULONG Reserved);
auto pNtCreateKeyedEvent = (__NtCreateKeyedEvent)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreateKeyedEvent");
HANDLE keyed_event;
if (pNtCreateKeyedEvent) pNtCreateKeyedEvent(&keyed_event, EVENT_ALL_ACCESS, NULL, 0);
typedef NTSTATUS(NTAPI *__NtCreatePort)(
OUT PHANDLE PortHandle,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG MaxConnectInfoLength,
IN ULONG MaxDataLength,
IN OUT PULONG Reserved OPTIONAL);
auto pNtCreatePort = (__NtCreatePort)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreatePort");
HANDLE lpc;
if (pNtCreatePort) {
OBJECT_ATTRIBUTES oa;
UNICODE_STRING port_name;
port_name.Buffer = L"\\0xbaddbadd";
port_name.Length = sizeof(L"\\0xbaddbadd");
port_name.MaximumLength = port_name.Length;
InitializeObjectAttributes(&oa, &port_name, 0, NULL, NULL);
pNtCreatePort(&lpc, &oa, 0, 0, NULL);
}
typedef NTSTATUS(NTAPI *__NtCreateTimer)(
OUT PHANDLE TimerHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN int TimerType);
auto pNtCreateTimer = (__NtCreateTimer)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreateTimer");
HANDLE timer;
if (pNtCreateTimer)
pNtCreateTimer(&timer, TIMER_ALL_ACCESS, NULL, 0);
UNONE::PsEnumHandle(GetCurrentProcessId(), [&](SYSTEM_HANDLE_TABLE_ENTRY_INFO &info)->bool {
HANDLE hd = (HANDLE)info.HandleValue;
if (hd == file) {
ObjectTypeTable[info.ObjectTypeIndex] = L"File";
} else if (hd == iocp) {
ObjectTypeTable[info.ObjectTypeIndex] = L"IoCompletion";
} else if (hd == desktop) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Desktop";
} else if (hd == event) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Event";
} else if (hd == mutant) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Mutant";
} else if (hd == semaphore) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Semaphore";
} else if (hd == section) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Section";
} else if (hd == station) {
ObjectTypeTable[info.ObjectTypeIndex] = L"WindowStation";
} else if (hd == key) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Key";
} else if (hd == keyed_event) {
ObjectTypeTable[info.ObjectTypeIndex] = L"KeyedEvent";
} else if (hd == lpc) {
if (UNONE::OsMajorVer() >= 6)
ObjectTypeTable[info.ObjectTypeIndex] = L"ALPC Port";
else
ObjectTypeTable[info.ObjectTypeIndex] = L"LPC Port";
} else if (hd == timer) {
ObjectTypeTable[info.ObjectTypeIndex] = L"Timer";
}
return true;
});
CloseHandle(file);
CloseHandle(iocp);
CloseHandle(event);
CloseHandle(mutant);
CloseHandle(semaphore);
CloseHandle(section);
RegCloseKey(key);
CloseHandle(lpc);
CloseHandle(timer);
}
int GetObjectTypeIndex(wchar_t* name)
{
for (auto kv : ObjectTypeTable) {
if (kv.second == L"File") return kv.first;
}
return 0;
}
std::string MbiTypeToString(int type)
{
std::string str;
if (type & MEM_PRIVATE) str += "MEM_PRIVATE | ";
if (type & MEM_IMAGE) str += "MEM_IMAGE | ";
if (type & MEM_MAPPED) str += "MEM_MAPPED | ";
return str.empty() ? "" : str.substr(0, str.size() - 3);
}
std::string MbiStateToString(int type)
{
std::string str;
if (type & MEM_COMMIT) str += "MEM_COMMIT | ";
if (type & MEM_FREE) str += "MEM_FREE | ";
if (type & MEM_RESERVE) str += "MEM_RESERVE | ";
return str.empty() ? "" : str.substr(0, str.size() - 3);
}
std::string MbiPageProtectToString(int type)
{
std::string str;
if (type & PAGE_EXECUTE) str += "PAGE_EXECUTE | ";
if (type & PAGE_EXECUTE_READ) str += "PAGE_EXECUTE_READ | ";
if (type & PAGE_EXECUTE_READWRITE) str += "PAGE_EXECUTE_READWRITE | ";
if (type & PAGE_EXECUTE_WRITECOPY) str += "PAGE_EXECUTE_WRITECOPY | ";
if (type & PAGE_NOACCESS) str += "PAGE_NOACCESS | ";
if (type & PAGE_READONLY) str += "PAGE_READONLY | ";
if (type & PAGE_READWRITE) str += "PAGE_READWRITE | ";
if (type & PAGE_GUARD) str += "PAGE_GUARD | ";
if (type & PAGE_NOCACHE) str += "PAGE_NOCACHE | ";
if (type & PAGE_WRITECOMBINE) str += "PAGE_WRITECOMBINE | ";
return str.empty() ? "" : str.substr(0, str.size() - 3);
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/cmds/constants/constants.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <Windows.h>
#include <string>
#include <map>
extern char *MessageRawString;
extern std::map<int, std::wstring> ObjectTypeTable;
extern std::map<int, std::string> MessageMapTable;
void InitObjectTypeTable();
int GetObjectTypeIndex(wchar_t* name);
std::string MbiTypeToString(int type);
std::string MbiStateToString(int type);
std::string MbiPageProtectToString(int type);
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/coderkit/coderkit.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "coderkit.h"
#include "../common/common.h"
#include "../openark/openark.h"
#include <locale>
#include <codecvt>
#if (!_DLL) && (_MSC_VER >= 1900 /* VS 2015*/) && (_MSC_VER <= 1911 /* VS 2017 */)
std::locale::id std::codecvt<char16_t, char, _Mbstatet>::id;
#endif
typedef std::wstring_convert<std::codecvt_utf8<int16_t>, int16_t> U16Convert;
typedef U16Convert::wide_string U16;
typedef std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> U32Convert;
typedef U32Convert::wide_string U32;
// Algorithm index
struct {
int s = 0;
int base64 = s++;
int crc32 = s++;
int md5 = s++;
int sha1 = s++;
int rc4 = s++;
int urlencode = s++;
int urldecode = s++;
int urlencodeURL = s++;
int urldecodeURL = s++;
} IDX;
struct {
int s = 0;
int x64 = s++;
int x86 = s++;
int x86_16 = s++;
int arm64 = s++;
int arm32 = s++;
int arm16 = s++;
int mips64 = s++;
int mips32 = s++;
int mips16 = s++;
} CPUPLATFORM_IDX;
enum InstrPlatform {
X64,
X86,
X86_16,
ARM64,
ARM32,
ARM16,
MIPS64,
MIPS32,
MIPS16,
};
enum ByteOrder {
LITTLE_ENDIAN,
BIG_ENDIAN,
};
CoderKit::CoderKit(QWidget* parent, int tabid) :
CommonMainTabObject::CommonMainTabObject((OpenArk*)parent)
{
ui.setupUi(this);
connect(OpenArkLanguage::Instance(), &OpenArkLanguage::languageChaned, this, [this]() {ui.retranslateUi(this); });
radio_group_type_.addButton(ui.nullRadio_2, 0);
radio_group_type_.addButton(ui.spaceRadio_2, 1);
radio_group_type_.addButton(ui.slashxRadio_2, 2);
radio_group_type_.addButton(ui.assembleRadio, 3);
radio_group_interval_.addButton(ui.byteRadio, 0);
radio_group_interval_.addButton(ui.twoBytesRadio, 1);
radio_group_interval_.addButton(ui.fourBytesRadio, 2);
ui.nullRadio_2->setChecked(true);
ui.byteRadio->setChecked(true);
connect(ui.nullRadio_2, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.spaceRadio_2, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.slashxRadio_2, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.assembleRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.byteRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.twoBytesRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.fourBytesRadio, SIGNAL(clicked()), this, SLOT(onFormatChanged()));
connect(ui.textEdit, SIGNAL(textChanged()), this, SLOT(onCodeTextChanged()));
connect(ui.defaultEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.asciiEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.unicodeEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.utf7Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.utf8Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.utf16Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.butf16Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.utf32Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.butf32Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.gbkEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.big5Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.cp866Edit, SIGNAL(textChanged(const QString &)), this, SLOT(onCodeTextChanged(const QString &)));
connect(ui.doserrEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onWindowsErrorTextChanged(const QString &)));
connect(ui.ntstatusEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onWindowsErrorTextChanged(const QString &)));
connect(ui.hresultEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onWindowsErrorTextChanged(const QString &)));
connect(ui.msgidBtn, SIGNAL(clicked()), this, SLOT(onMessageId()));
alg_idx_ = 0;
is_user_ = false;
is_format_changed_ = false;
onAlgIndexChanged(alg_idx_);
// ui.typeBox->insertItem(IDX.base64, "Base64");
// ui.typeBox->insertItem(IDX.crc32, "CRC32");
// ui.typeBox->insertItem(IDX.md5, "MD5");
// ui.typeBox->insertItem(IDX.sha1, "SHA1");
// ui.typeBox->insertItem(IDX.rc4, "RC4");
ui.base64Radio->setChecked(true);
connect(ui.base64Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
connect(ui.crc32Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
connect(ui.md5Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
connect(ui.sha1Radio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
connect(ui.urlencodeRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
connect(ui.urldecodeRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
// connect(ui.urlencodeURLRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
// connect(ui.urldecodeURLRadio, SIGNAL(clicked()), this, SLOT(onAlgPlainChanged()));
//connect(ui.typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onAlgIndexChanged(int)));
connect(ui.plainEdit, SIGNAL(textChanged()), this, SLOT(onAlgPlainChanged()));
connect(ui.cipherEdit, SIGNAL(textChanged()), this, SLOT(onAlgPlainChanged()));
//connect(ui.keyEdit, SIGNAL(textChanged()), this, SLOT(onAlgPlainChanged()));
InitAsmToolsView();
CommonMainTabObject::Init(ui.tabWidget, tabid);
}
CoderKit::~CoderKit()
{
}
void CoderKit::onTabChanged(int index)
{
CommonMainTabObject::onTabChanged(index);
}
void CoderKit::onCodeTextChanged()
{
std::wstring data;
std::string str;
QObject* sender = QObject::sender();
if (sender == ui.textEdit || is_format_changed_) {
data = ui.textEdit->toPlainText().toStdWString();
is_format_changed_ = false;
}
UpdateEditCodeText(data, sender);
}
void CoderKit::onCodeTextChanged(const QString & text)
{
QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender());
sender->setStyleSheet("background-color:white");
try {
std::string str = sender->text().toStdString();
std::wstring data;
auto InputFilter = [&](std::string& input) {
UNONE::StrReplaceA(input, "-");
UNONE::StrReplaceA(input, " ");
UNONE::StrReplaceA(input, "0x");
UNONE::StrReplaceA(input, "h");
UNONE::StrReplaceA(input, "\\x");
sender->setText(StrToQ(input));
};
is_user_ = ui.defaultEdit->isModified()
|| ui.asciiEdit->isModified()
|| ui.unicodeEdit->isModified()
|| ui.utf7Edit->isModified()
|| ui.utf8Edit->isModified()
|| ui.utf16Edit->isModified()
|| ui.butf16Edit->isModified()
|| ui.utf32Edit->isModified()
|| ui.butf32Edit->isModified()
|| ui.gbkEdit->isModified()
|| ui.big5Edit->isModified()
|| ui.cp866Edit->isModified();
if (is_user_) {
InputFilter(str);
} else {
return;
}
str = UNONE::StrHexStrToStreamA(str);
if (sender == ui.defaultEdit) {
data = UNONE::StrACPToWide(str);
} else if (sender == ui.asciiEdit) {
data = UNONE::StrCodeToWide(437, str);
} else if (sender == ui.unicodeEdit) {
data = std::wstring((wchar_t*)str.c_str(), str.size() / 2);
} else if (sender == ui.utf7Edit) {
data = UNONE::StrCodeToWide(CP_UTF7, str);
} else if (sender == ui.utf8Edit) {
data = UNONE::StrCodeToWide(CP_UTF8, str);
} else if (sender == ui.utf16Edit) {
data = std::wstring((wchar_t*)str.c_str(), str.size() / 2);
} else if (sender == ui.butf16Edit) {
str = UNONE::StrReverseA(str, 2);
data = std::wstring((wchar_t*)str.c_str(), str.size() / 2);
} else if (sender == ui.utf32Edit) {
U32 utf32((int32_t*)str.c_str(), str.size() / 4);
data = UNONE::StrUTF8ToWide(U32Convert().to_bytes(utf32));
} else if (sender == ui.butf32Edit) {
str = UNONE::StrReverseA(str, 4);
U32 utf32((int32_t*)str.c_str(), str.size() / 4);
data = UNONE::StrUTF8ToWide(U32Convert().to_bytes(utf32));
} else if (sender == ui.gbkEdit) {
data = UNONE::StrCodeToWide(936, str);
} else if (sender == ui.big5Edit) {
data = UNONE::StrCodeToWide(950, str);
} else if (sender == ui.cp866Edit) {
data = UNONE::StrCodeToWide(866, str);
}
UpdateEditCodeText(data, sender);
} catch(...) {
sender->setStyleSheet("background-color:red");
}
}
void CoderKit::onWindowsErrorTextChanged(const QString & text)
{
std::string number = text.toStdString();
QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender());
if (sender == ui.doserrEdit) {
auto err = VariantInt(number, 10);
auto msg = UNONE::StrFormatW(L"%d: %s", err, UNONE::OsDosErrorMsgW(err).c_str());
ui.msgEdit->setText(WStrToQ(msg));
} else if (sender == ui.ntstatusEdit) {
auto err = VariantInt(number, 16);
auto doserr = UNONE::OsNtToDosError((VariantInt(number, 16)));
auto msg = UNONE::StrFormatW(L"%X: %s", err, UNONE::OsDosErrorMsgW(doserr).c_str());
ui.doserrEdit->setText(QString("%1").arg(doserr));
ui.msgEdit->setText(WStrToQ(msg));
} else if (sender == ui.hresultEdit) {
auto hr = VariantInt(number, 16);
auto doserr = hr & 0xFFFF;
ui.doserrEdit->setText(QString("%1").arg(doserr));
auto msg = UNONE::StrFormatW(L"%X: %s", hr, UNONE::OsDosErrorMsgW(doserr).c_str());
ui.msgEdit->setText(WStrToQ(msg));
}
}
void CoderKit::onMessageId()
{
parent_->onExecCmd(L".msg");
MsgBoxInfo(tr("Open console to view result"));
}
void CoderKit::onAlgIndexChanged(int index)
{
alg_idx_ = index;
auto e_key = ui.keyEdit;
auto e_plain = ui.plainEdit;
auto l_plain = ui.keyLabel;
auto e_cipher = ui.cipherEdit;
e_key->hide();
l_plain->hide();
if (index == IDX.rc4) {
e_key->show();
l_plain->show();
UpdateAlgorithmText(false);
return;
}
UpdateAlgorithmText(true);
return;
}
void CoderKit::onAlgPlainChanged()
{
auto sender = qobject_cast<QTextEdit*>(QObject::sender());
if (sender == ui.plainEdit) {
UpdateAlgorithmText(true);
} else if (sender == ui.cipherEdit) {
UpdateAlgorithmText(false);
} else if (sender == ui.keyEdit) {
UpdateAlgorithmText(true);
}
auto sender_radio = qobject_cast<QRadioButton*>(QObject::sender());
if (sender_radio == ui.base64Radio) {
alg_idx_ = 0;
} else if (sender_radio == ui.crc32Radio) {
alg_idx_ = 1;
} else if (sender_radio == ui.md5Radio) {
alg_idx_ = 2;
} else if (sender_radio == ui.sha1Radio) {
alg_idx_ = 3;
} else if (sender_radio == ui.urlencodeRadio) {
alg_idx_ = 5;
} else if (sender_radio == ui.urldecodeRadio) {
alg_idx_ = 6;
// } else if (sender_radio == ui.urlencodeURLRadio) {
// alg_idx_ = 7;
// } else if (sender_radio == ui.urldecodeURLRadio) {
// alg_idx_ = 8;
} else {
return;
}
UpdateAlgorithmText(true);
}
void CoderKit::onFormatChanged()
{
is_format_changed_ = true;
onCodeTextChanged();
}
void CoderKit::InitAsmToolsView()
{
ui.splitter->setStretchFactor(0, 1);
ui.splitter->setStretchFactor(1, 2);
ui.nullRadio->setChecked(true);
connect(ui.asmBtn, &QPushButton::clicked, this, [&]() {
if (!UNONE::OsIs64()) { MsgBoxError("The feature not support 32bits os."); return; }
ByteOrder byteorder = LITTLE_ENDIAN;
auto byteorder_idx = ui.byteorderBox->currentIndex();
if (byteorder_idx == 0) byteorder = LITTLE_ENDIAN;
else if (byteorder_idx == 1) byteorder = BIG_ENDIAN;
InstrPlatform cpu = X64;
auto idx = ui.platformBox->currentIndex();
if (idx == CPUPLATFORM_IDX.x64) cpu = X64;
else if (idx == CPUPLATFORM_IDX.x86) cpu = X86;
else if (idx == CPUPLATFORM_IDX.x86_16) cpu = X86_16;
else if (idx == CPUPLATFORM_IDX.arm64) cpu = ARM64;
else if (idx == CPUPLATFORM_IDX.arm32) cpu = ARM32;
else if (idx == CPUPLATFORM_IDX.arm16) cpu = ARM16;
else if (idx == CPUPLATFORM_IDX.mips64) cpu = MIPS64;
else if (idx == CPUPLATFORM_IDX.mips32) cpu = MIPS32;
else if (idx == CPUPLATFORM_IDX.mips16) cpu = MIPS16;
auto &&in = ui.asmEdit->toPlainText().toStdString();
std::string formats;
if (ui.nullRadio->isChecked()) formats = "";
else if (ui.spaceRadio->isChecked()) formats = " ";
else if (ui.slashxRadio->isChecked()) formats = "\\x";
auto &&out = Rasm2Asm(in, cpu, byteorder, formats);
ui.disasmEdit->setText(out);
});
connect(ui.disasmBtn, &QPushButton::clicked, this, [&]() {
if (!UNONE::OsIs64()) { MsgBoxError("The feature not support 32bits os."); return; }
ByteOrder byteorder = LITTLE_ENDIAN;
auto byteorder_idx = ui.byteorderBox->currentIndex();
if (byteorder_idx == 0) byteorder = LITTLE_ENDIAN;
else if (byteorder_idx == 1) byteorder = BIG_ENDIAN;
InstrPlatform cpu = X64;
auto idx = ui.platformBox->currentIndex();
if (idx == CPUPLATFORM_IDX.x64) cpu = X64;
else if (idx == CPUPLATFORM_IDX.x86) cpu = X86;
else if (idx == CPUPLATFORM_IDX.x86_16) cpu = X86_16;
else if (idx == CPUPLATFORM_IDX.arm64) cpu = ARM64;
else if (idx == CPUPLATFORM_IDX.arm32) cpu = ARM32;
else if (idx == CPUPLATFORM_IDX.arm16) cpu = ARM16;
else if (idx == CPUPLATFORM_IDX.mips64) cpu = MIPS64;
else if (idx == CPUPLATFORM_IDX.mips32) cpu = MIPS32;
else if (idx == CPUPLATFORM_IDX.mips16) cpu = MIPS16;
auto &&in = ui.asmEdit->toPlainText().toStdString();
const char *pfx = "file:///";
auto pos = in.find(pfx);
if (pos == 0) {
auto file = UNONE::StrToW(in.substr(pos + strlen(pfx)));
UNONE::FsReadFileDataW(file, in);
in = UNONE::StrStreamToHexStrA(in);
} else {
UNONE::StrReplaceA(in, " ");
UNONE::StrReplaceA(in, "\\x");
}
if (in.size() >= 10 * KB) {
auto msbox = QMessageBox::warning(this, tr("Warning"),
tr("Your input data so much(suggest less 10 KB), it'll be very slowly, continue?"),
QMessageBox::Yes | QMessageBox::No);
if (msbox == QMessageBox::No) return;
}
auto &&out = Rasm2Disasm(in, cpu, byteorder);
ui.disasmEdit->setText(out);
});
}
void CoderKit::UpdateAlgorithmText(bool crypt)
{
auto e_key = ui.keyEdit;
std::string key = e_key->toPlainText().toStdString();
auto e_plain = ui.plainEdit;
std::string plain = e_plain->toPlainText().toStdString();
auto e_cipher = ui.cipherEdit;
std::string cipher;
if (alg_idx_ == IDX.base64) {
if (crypt) {
cipher = Cryptor::Base64Encode(plain);
} else {
cipher = e_cipher->toPlainText().toStdString();
plain = Cryptor::Base64Decode(cipher);
e_plain->blockSignals(true);
e_plain->setText(StrToQ(plain));
e_plain->blockSignals(false);
return;
}
} else if (alg_idx_ == IDX.crc32) {
auto val = Cryptor::GetCRC32ByData(plain);
cipher = UNONE::StrFormatA("%x", val);
} else if (alg_idx_ == IDX.md5) {
cipher = Cryptor::GetMD5ByData(plain);
cipher = UNONE::StrStreamToHexStrA(cipher);
} else if (alg_idx_ == IDX.sha1) {
cipher = Cryptor::GetSHA1ByData(plain);
cipher = UNONE::StrStreamToHexStrA(cipher);
} else if (alg_idx_ == IDX.rc4) {
cipher = Cryptor::GetSHA1ByData(plain);
} else if (alg_idx_ == IDX.urlencode) {
std::vector<char> pass;
std::vector<std::string> headers = { "http", "https", "ftp" };
for (auto h : headers) {
if (UNONE::StrIndexIA(plain, h) == 0) {
pass = { ':', '&', '/', '?', '=' };
break;
}
}
cipher = UrlEncode(plain, pass);
} else if (alg_idx_ == IDX.urldecode) {
cipher = UrlDecode(plain);
} else if (alg_idx_ == IDX.urlencodeURL) {
cipher = UrlEncodeURL(plain);
} else if (alg_idx_ == IDX.urldecodeURL) {
cipher = UrlDecode(plain);
}
if (!crypt) return;
e_cipher->blockSignals(true);
e_cipher->setText(StrToQ(cipher));
e_cipher->blockSignals(false);
}
void CoderKit::UpdateEditCodeText(const std::wstring& data, QObject* ignored_obj)
{
//prevent multi call simultaneously
std::unique_lock<std::mutex> guard(upt_mutex_, std::try_to_lock);
if (!guard.owns_lock()) return;
auto SetText = [&](QObject* obj, std::string data) {
if (obj == ignored_obj) return;
const char* class_name = obj->metaObject()->className();
if (class_name == QStringLiteral("QTextEdit")) {
qobject_cast<QTextEdit*>(obj)->setText(StrToQ(data));
} else if (class_name == QStringLiteral("QLineEdit")) {
data = UNONE::StrTrimA(data);
qobject_cast<QLineEdit*>(obj)->setText(StrToQ(data));
}
};
is_user_ = false;
int interval = 2;
int id_interval = radio_group_interval_.checkedId();
if (id_interval == 0) interval = 2;
else if (id_interval == 1) interval = 4;
else if (id_interval == 2) interval = 8;
std::string format = "";
int id_format = radio_group_type_.checkedId();
if (id_format == 0) format = "";
else if (id_format == 1) format = " ";
else if (id_format == 2) format = "\\x";
else if (id_format == 3) format = "h, ", interval = 2;
std::string text;
text = UNONE::StrWideToUTF8(data);
SetText(ui.textEdit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrWideToACP(data));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.defaultEdit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrACPToCode(437, UNONE::StrToA(data)));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.asciiEdit, text);
text = UNONE::StrStreamToHexStrA(std::string((char*)data.c_str(), data.size() * 2));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.unicodeEdit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(CP_UTF7, data));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.utf7Edit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(CP_UTF8, data));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.utf8Edit, text);
text = UNONE::StrStreamToHexStrA(std::string((char*)data.c_str(), data.size() * 2));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.utf16Edit, text);
auto stream = std::string((char*)data.c_str(), data.size() * 2);
stream = UNONE::StrReverseA(stream, 2);
text = UNONE::StrStreamToHexStrA(stream);
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.butf16Edit, text);
U32Convert cvt32;
auto utf32 = cvt32.from_bytes(UNONE::StrWideToCode(CP_UTF8, data));
stream = std::string((char*)utf32.c_str(), utf32.size() * 4);
text = UNONE::StrStreamToHexStrA(stream);
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.utf32Edit, text);
stream = UNONE::StrReverseA(stream, 4);
text = UNONE::StrStreamToHexStrA(stream);
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.butf32Edit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(936, data));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.gbkEdit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(950, data));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.big5Edit, text);
text = UNONE::StrStreamToHexStrA(UNONE::StrWideToCode(866, data));
SolveCodeTextFormat(text, format, interval, id_format);
SetText(ui.cp866Edit, text);
}
QString CoderKit::Rasm2Asm(std::string data, int cpu, int byteorder, const std::string &format)
{
auto &&rasm2 = AppConfigDir() + L"\\nasm\\rasm2.exe";
if (!UNONE::FsIsExistedW(rasm2)) {
ExtractResource(":/OpenArk/nasm/rasm2.exe", WStrToQ(rasm2));
}
auto &&tmp_out = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.bin");
auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.asm");
UNONE::FsWriteFileDataW(tmp_in, data);
int bits;
std::wstring plat;
switch (cpu) {
case X64: plat = L"x86"; bits = 64; break;
case X86: plat = L"x86"; bits = 32; break;
case X86_16: plat = L"x86"; bits = 16; break;
case ARM64: plat = L"arm"; bits = 64; break;
case ARM32: plat = L"arm"; bits = 32; break;
case ARM16: plat = L"arm"; bits = 16; break;
case MIPS64: plat = L"mips"; bits = 64; break;
case MIPS32: plat = L"mips"; bits = 32; break;
case MIPS16: plat = L"mips"; bits = 16; break;
}
auto &&cmdline = rasm2;
if (byteorder == BIG_ENDIAN) cmdline += L" -e";
cmdline = UNONE::StrFormatW(L"%s -a %s -b%d -O \"%s\" -f \"%s\"",
rasm2.c_str(), plat.c_str(), bits,
tmp_out.c_str(), tmp_in.c_str());
std::wstring out;
DWORD exitcode;
QString err_prefix = tr("Compile Error:\n--------------------------------------------------------------\n");
auto ret = ReadStdout(cmdline, out, exitcode);
if (!ret) return err_prefix + tr("run compiler error");
if (exitcode != 0) return err_prefix + WStrToQ(out);
std::string bin;
UNONE::FsReadFileDataW(tmp_out, bin);
bin = UNONE::StrTrimA(bin);
bin = format + UNONE::StrInsertA(bin, 2, format);
return StrToQ(bin);
}
QString CoderKit::Rasm2Disasm(std::string data, int cpu, int byteorder)
{
auto &&rasm2 = AppConfigDir() + L"\\nasm\\rasm2.exe";
if (!UNONE::FsIsExistedW(rasm2)) {
ExtractResource(":/OpenArk/nasm/rasm2.exe", WStrToQ(rasm2));
}
auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-ndisasm-code.bin");
UNONE::FsWriteFileDataW(tmp_in, data);
int bits;
std::wstring plat;
switch (cpu) {
case X64: plat = L"x86"; bits = 64; break;
case X86: plat = L"x86"; bits = 32; break;
case X86_16: plat = L"x86"; bits = 16; break;
case ARM64: plat = L"arm"; bits = 64; break;
case ARM32: plat = L"arm"; bits = 32; break;
case ARM16: plat = L"arm"; bits = 16; break;
case MIPS64: plat = L"mips"; bits = 64; break;
case MIPS32: plat = L"mips"; bits = 32; break;
case MIPS16: plat = L"mips"; bits = 16; break;
}
auto &&cmdline = rasm2;
if (byteorder == BIG_ENDIAN) cmdline += L" -e";
cmdline = UNONE::StrFormatW(L"%s -a %s -b%d -D -f \"%s\"",
cmdline.c_str(), plat.c_str(), bits,
tmp_in.c_str());
std::wstring out;
DWORD exitcode;
auto ret = ReadStdout(cmdline, out, exitcode);
if (!ret) return tr("run disassember error");
UNONE::StrLowerW(out);
//UNONE::StrReplaceW(out, L" ", L" ");
return WStrToQ(out);
}
QString CoderKit::NasmAsm(std::string data, int bits, const std::string &format)
{
if (bits == 64) data.insert(0, "[bits 64]\n");
else if (bits == 32) data.insert(0, "[bits 32]\n");
else if (bits == 16) data.insert(0, "[bits 16]\n");
auto &&nasm = AppConfigDir() + L"\\nasm\\nasm.exe";
if (!UNONE::FsIsExistedW(nasm)) {
ExtractResource(":/OpenArk/nasm/nasm.exe", WStrToQ(nasm));
}
auto &&tmp_out = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.bin");
auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-nasm-code.asm");
UNONE::FsWriteFileDataW(tmp_in, data);
auto &&cmdline = UNONE::StrFormatW(L"%s -f bin -o \"%s\" \"%s\"", nasm.c_str(), tmp_out.c_str(), tmp_in.c_str());
std::wstring out;
DWORD exitcode;
QString err_prefix = tr("Compile Error:\n--------------------------------------------------------------\n");
auto ret = ReadStdout(cmdline, out, exitcode);
if (!ret) return err_prefix + tr("start nasm error");
if (exitcode != 0) return err_prefix + WStrToQ(out);
std::string bin;
UNONE::FsReadFileDataW(tmp_out, bin);
bin = UNONE::StrStreamToHexStrA(bin);
bin = format + UNONE::StrInsertA(bin, 2, format);
return StrToQ(bin);
}
QString CoderKit::NasmDisasm(const std::string &data, int bits)
{
auto &&ndisasm = AppConfigDir() + L"\\nasm\\ndisasm.exe";
if (!UNONE::FsIsExistedW(ndisasm)) {
ExtractResource(":/OpenArk/nasm/ndisasm.exe", WStrToQ(ndisasm));
}
auto &&tmp_in = UNONE::OsEnvironmentW(L"%Temp%\\temp-ndisasm-code.bin");
UNONE::FsWriteFileDataW(tmp_in, data);
auto &&cmdline = UNONE::StrFormatW(L"%s -b %d \"%s\"", ndisasm.c_str(), bits, tmp_in.c_str());
std::wstring out;
DWORD exitcode;
auto ret = ReadStdout(cmdline, out, exitcode);
if (!ret) return tr("start ndisasm error");
UNONE::StrLowerW(out);
return WStrToQ(out);
}
void CoderKit::SolveCodeTextFormat(std::string &text, std::string &format, int interval, int id)
{
if (id == 3) {
// assemble
text = UNONE::StrInsertA(text, interval, format);
text = text + "h";
} else {
text = format + UNONE::StrInsertA(text, interval, format);
}
}
#ifndef HEX_TO_UPPER_CHAR
#define HEX_TO_UPPER_CHAR(x) ((unsigned char)(x) > 9 ? (unsigned char)(x) -10 + 'A': (unsigned char)(x) + '0')
#endif
//'1' => 1 / 'A' => A
#ifndef UPPER_CHAR_TO_HEX
#define UPPER_CHAR_TO_HEX(x) (isdigit((unsigned char)(x)) ? (unsigned char)(x)-'0' : (unsigned char)(toupper(x))-'A'+10)
#endif
static const char* kUrlReservedCharset = "!*'();:@&=+$,/?#[]";
static const char* kUrlNonReservedCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
std::string CoderKit::UrlEncode(const std::string &buf, std::vector<char> pass)
{
std::string str;
try {
std::string CharSet = kUrlNonReservedCharset;
for (size_t i = 0; i < buf.size(); i++) {
unsigned char temp[4] = {0};
unsigned char ch = static_cast<unsigned char>(buf[i]);
bool found = false;
for (auto p : pass) {
if (p == ch) {
found = true;
break;
}
}
if (found || CharSet.find(ch) != std::string::npos) {
temp[0] = ch;
} else {
temp[0] = '%';
temp[1] = HEX_TO_UPPER_CHAR(ch >> 4);
temp[2] = HEX_TO_UPPER_CHAR(ch & 0x0F);
}
str += (char*)temp;
}
} catch (std::exception& e) {
str.clear();
} catch (...) {
str.clear();
}
return std::move(str);
}
std::string CoderKit::UrlDecode(const std::string &buf)
{
std::string str;
try {
std::string bits;
bits.assign(buf.size(), 0);
for (size_t i = 0; i < buf.size(); i++) {
if (buf[i]=='%') {
bits[i] = 1;
bits[i+1] = 1;
bits[i+2] = 1;
i += 2;
}
}
auto& decode = [](std::string& s)->std::string {
std::string out;
for (size_t i = 0; i < s.size(); i+=3) {
unsigned char ch = 0;
if (s[i] != '%')
continue;
ch = UPPER_CHAR_TO_HEX(s[i+1]) << 4;
ch |= (UPPER_CHAR_TO_HEX(s[i+2]) & 0x0F);
out.push_back(ch);
}
//out = StrUTF8ToGBK(out);
return out;
};
size_t last = 0;
size_t i = 0;
for (i=0; i<bits.size(); i++) {
if (bits[i] == 0) {
if (last < i) {
str += decode(buf.substr(last, i-last));
}
str += buf[i];
last = i + 1;
}
}
//处理边界情况
if (bits.size() && bits.back() == 1) {
if (last < i) {
str += decode(buf.substr(last, i-last));
}
}
} catch (std::exception& e) {
str.clear();
} catch (...) {
str.clear();
}
return std::move(str);
}
bool IsValidUrlChar(char ch, bool unsafe_only) {
if (static_cast<unsigned>(ch) < 0 || static_cast<unsigned>(ch) > 127) {
return false;
}
if (unsafe_only) {
return !(ch <= ' ' || strchr("\\\"^&`<>[]{}", ch));
} else {
return isalnum(ch) || strchr("-_.!~*'()", ch);
}
}
static const char* kSpecialCharset = "/:?";
static const char* kNewUrlNonReservedCharset = "!*()ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
std::string CoderKit::UrlEncodeURL(const std::string &buf)
{
std::string source = buf;
std::string str;
try {
// for (size_t i = 0; i < buf.size(); i++) {
// unsigned char temp[4] = {0};
// unsigned char ch = static_cast<unsigned char>(buf[i]);
// if (char_set.find(ch) != std::string::npos) {
// temp[0] = ch;
// }
// else {
// if (!has_question_mark && (special_charset.find(ch) != std::string::npos)) {
// temp[0] = ch;
// has_question_mark = (ch == '?');
// } else if (!has_equal_mark && ch == '=') {
// temp[0] = ch;
// has_equal_mark = true;
// } else {
// temp[0] = '%';
// temp[1] = HEX_TO_UPPER_CHAR(ch >> 4);
// temp[2] = HEX_TO_UPPER_CHAR(ch & 0x0F);
// }
// }
// str += (char*)temp;
// }
} catch (std::exception& e) {
str.clear();
} catch (...) {
str.clear();
}
return std::move(str);
// size_t size = buf.size() + 5;
// std::unique_ptr<char[]> source_ptr(new char[size]);
// std::unique_ptr<char[]> dest_ptr(new char[size<<2]);
// strcpy(source_ptr.get(), buf.c_str());
// char *source = source_ptr.get();
// char *dest = dest_ptr.get();
// bool encode_space_as_plus = true;
// bool unsafe_only = false;
// static const char *digits = "0123456789ABCDEF";
// //if (max == 0) {
// // return 0;
// //}
// char *start = dest;
// while (*source) {
// unsigned char ch = static_cast<unsigned char>(*source);
// if (*source == ' ' && encode_space_as_plus && !unsafe_only) {
// *dest++ = '+';
// } else if (IsValidUrlChar(ch, unsafe_only)) {
// *dest++ = *source;
// } else {
// /*if (static_cast<unsigned>(dest - start) + 4 > max) {
// break;
// }*/
// *dest++ = '%';
// *dest++ = digits[(ch >> 4) & 0x0F];
// *dest++ = digits[ ch & 0x0F];
// }
// source++;
// }
// // ASSERT(static_cast<unsigned int>(dest - start) < max);
// *dest = 0;
// return std::move(dest_ptr.get());
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/coderkit/coderkit.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
#include <QMutex>
#include <qbuttongroup.h>
#include <Windows.h>
#include <mutex>
#include "ui_coderkit.h"
#include "../common/ui-wrapper/ui-wrapper.h"
namespace Ui {
class CoderKit;
class OpenArkWindow;
}
class OpenArk;
class CoderKit : public CommonMainTabObject {
Q_OBJECT
public:
CoderKit(QWidget* parent, int tabid);
~CoderKit();
private slots:
void onTabChanged(int index);
void onCodeTextChanged();
void onCodeTextChanged(const QString &text);
void onWindowsErrorTextChanged(const QString &text);
void onMessageId();
void onAlgIndexChanged(int index);
void onAlgPlainChanged();
void onFormatChanged();
private:
void InitAsmToolsView();
void UpdateAlgorithmText(bool crypt);
void UpdateEditCodeText(const std::wstring& data, QObject* ignored_obj);
QString Rasm2Asm(std::string data, int cpu, int byteorder, const std::string &format);
QString Rasm2Disasm(std::string data, int cpu, int byteorder);
QString NasmAsm(std::string data, int bits, const std::string &format);
QString NasmDisasm(const std::string &data, int bits);
void SolveCodeTextFormat(std::string &text, std::string &format, int interval, int id);
std::string UrlEncode(const std::string &buf, std::vector<char> pass);
std::string UrlDecode(const std::string &buf);
std::string UrlEncodeURL(const std::string &buf);
private:
Ui::CoderKit ui;
std::mutex upt_mutex_;
int alg_idx_;
bool is_user_;
bool is_format_changed_;
QButtonGroup radio_group_type_;
QButtonGroup radio_group_interval_;
}; | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/app/app.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "../common.h"
#include "app.h"
void LogOutput(LogOuputLevel lev, const char* func, const wchar_t* format, ...)
{
QString levelstr;
struct { int lev; QString levstr; } levels[] = {
{ LevelInfo , TR("[INFO]") },
{ LevelWarn , TR("<font color=red>[WARN]</font>") },
{ LevelErr , TR("<font color=red>[ERR]</font>") },
{ LevelDbg , TR("[DBG]") },
};
for (int i = 0; i < _countof(levels); i++) {
if (levels[i].lev == lev) {
levelstr = levels[i].levstr;
break;
}
}
std::wstring prefix = UNONE::StrFormatW(
TR("<font color=#E0E2E4>[%s] %s %s </font>").toStdWString().c_str(),
UNONE::StrToW(func).c_str(),
levelstr.toStdWString().c_str(),
format);
std::wstring str;
va_list lst;
va_start(lst, format);
str = UNONE::StrFormatVaListW(prefix.c_str(), lst);
va_end(lst);
openark->onLogOutput(QString::fromStdWString(str));
}
void LogOutput(LogOuputLevel lev, const char* func, const char* format, ...)
{
va_list lst;
va_start(lst, format);
std::wstring&& wstr = UNONE::StrToW(UNONE::StrFormatVaListA(format, lst));
LogOutput(lev, func, L"%s", wstr.c_str());
va_end(lst);
}
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/app/app.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <unone.h>
#include <QString>
enum LogOuputLevel { LevelInfo, LevelWarn, LevelErr, LevelDbg };
void LogOutput(LogOuputLevel lev, const char* func, const char* format, ...);
void LogOutput(LogOuputLevel lev, const char* func, const wchar_t* format, ...);
#define INFO(format, ...) \
LogOutput(LevelInfo, __FUNCTION__, (format), __VA_ARGS__)
#define WARN(format, ...) \
LogOutput(LevelWarn, __FUNCTION__, (format), __VA_ARGS__)
#define ERR(format, ...) \
LogOutput(LevelErr, __FUNCTION__, (format), __VA_ARGS__)
#define DBG(format, ...) \
LogOutput(LevelDbg, __FUNCTION__, (format), __VA_ARGS__)
#define QERR_A(format, ...) \
LogOutput(LevelErr, __FUNCTION__, (TRA(format)), __VA_ARGS__)
#define QERR_W(format, ...) \
LogOutput(LevelErr, __FUNCTION__, (TRW(format)), __VA_ARGS__)
inline QString AppFilePath()
{
return QString::fromStdWString(UNONE::PsGetProcessPathW());
}
inline QString AppVersion()
{
std::wstring ver;
UNONE::FsGetFileInfoW(UNONE::PsGetProcessPathW(), L"ProductVersion", ver);
if (!ver.empty()) {
ver = ver.substr(0, ver.find_last_of(L"."));
}
return QString::fromStdWString(ver);
}
inline QString AppBuildTime()
{
QString &&stamp = QString::fromStdString(UNONE::TmFormatUnixTimeA(UNONE::PeGetTimeStamp((CHAR*)GetModuleHandleW(NULL)), "YMDHW"));
return stamp;
}
inline std::wstring AppConfigDir()
{
static std::wstring dir;
if (!dir.empty()) return dir;
auto &&curdir = UNONE::PsGetProcessDirW();
auto &&cfg = curdir + L"\\openark.ini";
if (UNONE::FsIsExistedW(cfg)) {
dir = std::move(curdir);
return dir;
}
dir = UNONE::OsEnvironmentW(L"%AppData%") + L"\\OpenArk";
return dir;
}
inline QString AppFsUrl(QString url = "")
{
static QString fsurl;
if (url.isEmpty()) {
return fsurl;
}
fsurl = url;
return fsurl;
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/cache/cache.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "cache.h"
#include "../common.h"
#include <arkdrv-api/arkdrv-api.h>
static struct {
QMutex lck;
QMap<unsigned int, ProcInfo> d;
} proc_info;
ProcInfo CacheGetProcInfo(unsigned int pid)
{
ProcInfo info;
CacheGetProcInfo(pid, info);
return info;
}
ProcInfo CacheGetProcInfo(unsigned int pid, ProcInfo& info)
{
QMutexLocker locker(&proc_info.lck);
if (proc_info.d.contains(pid)) {
auto it = proc_info.d.find(pid);
info = it.value();
if (!info.path.isEmpty()) {
return info;
}
}
info.pid = pid;
if (info.ppid == -1) info.ppid = UNONE::PsGetParentPid(pid);
if (info.parent_existed == -1) {
// May be parent id occupied by someone implies parent not existed
info.parent_existed = 1;
auto ppid = info.ppid;
auto tm1 = ProcessCreateTimeValue(pid);
auto tm2 = ProcessCreateTimeValue(ppid);
if (UNONE::PsIsDeleted(ppid) || (tm1 && tm2 && tm1 < tm2))
info.parent_existed = 0;
}
bool activate = false;
auto &&path = UNONE::PsGetProcessPathW(pid);
if (path.empty()) {
UNONE::InterCreateTlsValue(ArkDrvApi::Process::OpenProcessR0, UNONE::PROCESS_VID);
path = UNONE::PsGetProcessPathW(pid);
activate = true;
}
static bool is_os64 = UNONE::OsIs64();
info.path = WStrToQ(path);
if (!path.empty() && path != L"System") {
std::wstring corp, desc;
UNONE::FsGetFileInfoW(path, L"CompanyName", corp);
UNONE::FsGetFileInfoW(path, L"FileDescription", desc);
info.corp = WStrToQ(corp);
info.desc = WStrToQ(desc);
}
if (info.name.isEmpty()) info.name = WStrToQ(UNONE::FsPathToNameW(path));
info.ctime = WStrToQ(ProcessCreateTime(pid));
if (is_os64 && !UNONE::PsIsX64(pid)) info.name.append(" *32");
proc_info.d.insert(pid, info);
if (activate) UNONE::InterDeleteTlsValue(UNONE::PROCESS_VID);
return info;
}
void CacheGetProcChilds(unsigned int pid, QVector<ProcInfo>& infos)
{
if (pid == 0) {
return;
}
QMutexLocker locker(&proc_info.lck);
for (auto &info : proc_info.d) {
if (info.parent_existed == 1 && info.ppid == pid) {
infos.push_back(info);
}
}
}
void CacheRefreshProcInfo()
{
QMutexLocker locker(&proc_info.lck);
auto &d = proc_info.d;
for (auto it = d.begin(); it != d.end(); ) {
auto pid = it.key();
if ((pid == INVALID_PID ) || (pid != 0 && UNONE::PsIsDeleted(pid))) {
d.erase(it++);
} else {
it++;
}
}
}
static struct {
QMutex lck;
QMap<unsigned int, UNONE::PROCESS_BASE_INFOW> d;
} proc_baseinfo;
UNONE::PROCESS_BASE_INFOW CacheGetProcessBaseInfo(DWORD pid)
{
UNONE::PROCESS_BASE_INFOW info;
QMutexLocker locker(&proc_baseinfo.lck);
if (proc_baseinfo.d.contains(pid)) {
auto it = proc_baseinfo.d.find(pid);
info = it.value();
if (!info.ImagePathName.empty())
return info;
}
bool activate = false;
UNONE::PsGetProcessInfoW(pid, info);
if (info.ImagePathName.empty()) {
UNONE::InterCreateTlsValue(ArkDrvApi::Process::OpenProcessR0, UNONE::PROCESS_VID);
UNONE::PsGetProcessInfoW(pid, info);
activate = true;
}
if (activate) UNONE::InterDeleteTlsValue(UNONE::PROCESS_VID);
proc_baseinfo.d.insert(pid, info);
return info;
}
static struct {
QMutex lck;
QMap<QString, FileBaseInfo> d;
} filebase_info;
FileBaseInfo CacheGetFileBaseInfo(QString path)
{
QMutexLocker locker(&filebase_info.lck);
if (filebase_info.d.contains(path)) {
auto it = filebase_info.d.find(path);
return it.value();
}
std::wstring corp, desc, ver;
auto w_path = path.toStdWString();
UNONE::FsGetFileInfoW(w_path, L"CompanyName", corp);
UNONE::FsGetFileInfoW(w_path, L"FileDescription", desc);
UNONE::FsGetFileVersionW(w_path, ver);
auto info = FileBaseInfo{ path, WStrToQ(desc), WStrToQ(ver), WStrToQ(corp) };
filebase_info.d.insert(path, info);
return info;
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/cache/cache.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <unone.h>
#include <QString>
#include <QVector>
#include <QMap>
#include <QMutex>
struct ProcInfo {
DWORD pid;
DWORD ppid = -1;
DWORD parent_existed = -1;
QString name;
QString desc;
QString corp;
QString ctime;
QString path;
};
ProcInfo CacheGetProcInfo(unsigned int pid);
ProcInfo CacheGetProcInfo(unsigned int pid, ProcInfo& info);
void CacheGetProcChilds(unsigned int pid, QVector<ProcInfo>& infos);
void CacheRefreshProcInfo();
UNONE::PROCESS_BASE_INFOW CacheGetProcessBaseInfo(DWORD pid);
struct FileBaseInfo {
QString path;
QString desc;
QString ver;
QString corp;
};
FileBaseInfo CacheGetFileBaseInfo(QString path); | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/common.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "common.h"
#include "../openark/openark.h"
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/common.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <unone.h>
using namespace UNONE::Plugins;
#include "win-wrapper/win-wrapper.h"
#include "qt-wrapper/qt-wrapper.h"
#include "cpp-wrapper/cpp-wrapper.h"
#include "app/app.h"
#include "cache/cache.h"
#include "config/config.h" | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/config/config.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "config.h"
#include "../common.h"
void OpenArkConfig::Init()
{
auto &&cpath = AppConfigDir() + L"\\openark.ini";
UNONE::FsCreateDirW(UNONE::FsPathToDirW(cpath));
appconf_ = new QSettings(WStrToQ(cpath), QSettings::IniFormat);
}
int OpenArkConfig::GetLang(ConfOp op, int &lang)
{
QString section = "/Main/";
QString key = section + "lang";
if (op == CONF_GET) {
lang = GetValue(key, -1).toInt();
return lang;
}
if (op == CONF_SET) {
SetValue(key, lang);
return lang;
}
return -1;
}
QStringList OpenArkConfig::GetJunkDirs()
{
QStringList dirs;
std::vector<std::wstring> junkdirs;
// Temp
junkdirs.push_back(UNONE::OsEnvironmentW(L"%Temp%"));
junkdirs.push_back(UNONE::OsEnvironmentW(L"%windir%\\Temp"));
// Recent
auto appdata = UNONE::OsEnvironmentW(L"%AppData%");
auto localappdata = UNONE::OsEnvironmentW(L"%LocalAppData%");
junkdirs.push_back(appdata + L"\\Microsoft\\Windows\\Recent");
junkdirs.push_back(appdata + L"\\Microsoft\\Office\\Recent");
// Chrome
junkdirs.push_back(localappdata + L"\\Google\\Chrome\\User Data\\Default\\Cache");
junkdirs.push_back(localappdata + L"\\Google\\Chrome\\User Data\\Default\\Code Cache");
// junkdirs.push_back(L"C:\\AppData\\Roaming");
return WVectorToQList(junkdirs);
}
QString OpenArkConfig::GetConsole(const QString &name)
{
QString section = "/Console/";
auto key = section + name;
if (name == "History.MaxRecords") {
return GetValue(key, "2000").toString();
}
if (name == "History.FilePath") {
auto &&default_path = AppConfigDir() + L"\\console\\history.txt";
if (!UNONE::FsIsExistedW(default_path)) {
UNONE::FsCreateDirW(UNONE::FsPathToDirW(default_path));
UNONE::FsWriteFileDataW(default_path, "");
}
return GetValue(key, WStrToQ(default_path)).toString();
}
return "";
}
void OpenArkConfig::GetMainGeometry(int &x, int &y, int &w, int &h)
{
QString section = "/Main/";
auto key = section + "x";
if (!(Contains(section + "x") || Contains(section + "y") ||
Contains(section + "w") || Contains(section + "h"))) {
return GetMainDefaultGeometry(x, y, w, h);
}
x = GetValue(section + "x").toInt();
y = GetValue(section + "y").toInt();
w = GetValue(section + "w").toInt();
h = GetValue(section + "h").toInt();
if (GetSystemMetrics(SM_CMONITORS) <= 1 && (x <= 0 || y <= 0))
OpenArkConfig::Instance()->GetMainDefaultGeometry(x, y, w, h);
}
void OpenArkConfig::GetMainDefaultGeometry(int &x, int &y, int &w, int &h)
{
QRect desk = QApplication::desktop()->availableGeometry();
double scale = (double)desk.height() / desk.width();
double width = desk.width() / 1.7;
double height = width * scale;
double pos_x = desk.width() / 8;
double pos_y = desk.height() / 8;
x = (int)pos_x;
y = (int)pos_y;
w = (int)width;
h = (int)height;
return;
}
void OpenArkConfig::SetMainGeometry(int x, int y, int w, int h)
{
QString section = "/Main/";
if (x != -1) SetValue(section + "x", x);
if (y != -1) SetValue(section + "y", y);
if (w != -1) SetValue(section + "w", w);
if (h != -1) SetValue(section + "h", h);
Sync();
}
void OpenArkConfig::GetMainMaxed(bool &maxed)
{
QString section = "/Main/";
maxed = GetValue(section + "maxed").toBool();;
}
void OpenArkConfig::SetMainMaxed(bool maxed)
{
QString section = "/Main/";
SetValue(section + "maxed", maxed);;
Sync();
}
void OpenArkConfig::GetPrefMainTab(int &idx)
{
QString section = "/Preference/";
idx = GetValue(section + "main_tab", idx).toInt();
}
void OpenArkConfig::SetPrefMainTab(int idx)
{
QString section = "/Preference/";
SetValue(section + "main_tab", idx);
Sync();
}
void OpenArkConfig::GetPrefLevel2Tab(int &idx)
{
QString section = "/Preference/";
idx = GetValue(section + "level2_tab", idx).toInt();
}
void OpenArkConfig::SetPrefLevel2Tab(int idx)
{
QString section = "/Preference/";
SetValue(section + "level2_tab", idx);
Sync();
}
void OpenArkConfig::SetMainTabMap(int seq, QVector<int> idx)
{
QString section = "/Preference/";
if (seq >= maintab_map_.size()) return;
QString s;
for (auto d : idx) {
s.append(QString("%1").arg(d, 2, 10, QChar('0')));
}
s = QString("%1%2").arg(idx.size()).arg(s);
maintab_map_[seq] = s;
QString serial;
for (int i = 0; i < maintab_map_.size(); i++) {
serial.append(maintab_map_[i]);
if (i == maintab_map_.size() - 1) break;
serial.append(":");
}
SetValue(section + "maintab_map", serial);
Sync();
}
void OpenArkConfig::GetMainTabMap(int seq, QVector<int> &idx)
{
QString section = "/Preference/";
QString str;
str = GetValue(section + "maintab_map").toString();
if (str.isEmpty()) {
for (int i = 0; i < TAB_MAX; i++) {
str.append("0");
if (i == TAB_MAX - 1) break;
str.append(":");
}
}
maintab_map_ = str.split(":").toVector();
if (seq >= maintab_map_.size()) return;
int cnt = maintab_map_[seq].mid(0, 1).toInt();
if (!cnt) return;
QString &back = maintab_map_[seq].mid(1);
for (int i = 0; i < back.size(); i+=2) {
idx.push_back(back.mid(i, 2).toInt());
}
}
void OpenArkConfig::GetMainTabAllMap(QVector<QVector<int>> &idxs)
{
QString section = "/Preference/";
QString str;
str = GetValue(section + "maintab_map").toString();
if (str.isEmpty()) {
for (int i = 0; i < TAB_MAX; i++) {
str.append("20000");
if (i == TAB_MAX - 1) break;
str.append(":");
}
}
for (int seq = 0; seq < TAB_MAX; seq++) {
QVector<int> idx;
maintab_map_ = str.split(":").toVector();
int cnt = maintab_map_[seq].mid(0, 1).toInt();
if (!cnt) return;
QString back = maintab_map_[seq].mid(1);
for (int i = 0; i < back.size(); i += 2) {
idx.push_back(back.mid(i, 2).toInt());
}
idxs.push_back(idx);
}
}
OpenArkConfig* OpenArkConfig::confobj_ = nullptr;
OpenArkConfig* OpenArkConfig::Instance()
{
if (confobj_) return confobj_;
confobj_ = new OpenArkConfig;
return confobj_;
}
OpenArkConfig::OpenArkConfig() {
}
OpenArkConfig::~OpenArkConfig() {
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/config/config.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <QString>
#include <QSettings>
#include <QVector>
enum ConfOp {
CONF_GET,
CONF_SET,
};
enum MainTabNumber {
TAB_PROCESS,
TAB_KERNEL,
TAB_CODERKIT,
TAB_SCANNER,
TAB_BUNDLER,
TAB_UTILITIES,
TAB_REVERSE,
TAB_MAX
};
static int def_lang_ = -1;
class OpenArkConfig {
public:
void Init();
static OpenArkConfig* Instance();
int GetLang(ConfOp op, int &lang = def_lang_);
QStringList GetJunkDirs();
QString GetConsole(const QString &name);
void GetMainGeometry(int &x, int &y, int &w, int &h);
void GetMainDefaultGeometry(int &x, int &y, int &w, int &h);
void SetMainGeometry(int x, int y, int w, int h);
void GetMainMaxed(bool &maxed);
void SetMainMaxed(bool maxed);
void GetPrefMainTab(int &idx);
void SetPrefMainTab(int idx);
void GetPrefLevel2Tab(int &idx);
void SetPrefLevel2Tab(int idx);
void SetMainTabMap(int seq, QVector<int> idx);
void GetMainTabMap(int seq, QVector<int> &idx);
void GetMainTabAllMap(QVector<QVector<int>> &idxs);
QVariant GetValue(const QString &key, const QVariant &defaultValue = QVariant()) const { return appconf_->value(key, defaultValue); };
void SetValue(const QString &key, const QVariant &value) { return appconf_->setValue(key, value); };
bool Contains(const QString &key) const { return appconf_->contains(key); }
void Sync() { return appconf_->sync(); };
private:
QSettings *appconf_;
QVector<QString> maintab_map_;
public:
static OpenArkConfig *confobj_;
OpenArkConfig();
~OpenArkConfig();
};
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/cpp-wrapper/cpp-wrapper.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "cpp-wrapper.h"
#include "../common/common.h"
int VariantInt(std::string val, int radix)
{
if (val.empty()) {
return 0;
}
if (val.find("0n") == 0) {
UNONE::StrReplaceA(val, "0n");
return UNONE::StrToDecimalA(val);
}
if (val.find("0x") == 0 || val[val.size() - 1] == 'h') {
UNONE::StrReplaceA(val, "0x");
return UNONE::StrToHexA(val);
}
if (val.find("0t") == 0) {
UNONE::StrReplaceA(val, "0t");
return UNONE::StrToOctalA(val);
}
if (val.find("0y") == 0) {
UNONE::StrReplaceA(val, "0y");
return UNONE::StrToBinaryA(val);
}
switch (radix) {
case 2: return UNONE::StrToBinaryA(val);
case 8: return UNONE::StrToOctalA(val);
case 10: return UNONE::StrToDecimalA(val);
case 16: return UNONE::StrToHexA(val);
default: return UNONE::StrToHexA(val);
}
}
int64_t VariantInt64(std::string val, int radix)
{
UNONE::StrReplaceA(val, "`");
if (val.empty()) {
return 0;
}
if (val.find("0n") == 0) {
UNONE::StrReplaceA(val, "0n");
return UNONE::StrToDecimal64A(val);
}
if (val.find("0x") == 0 || val[val.size() - 1] == 'h') {
UNONE::StrReplaceA(val, "0x");
return UNONE::StrToHex64A(val);
}
if (val.find("0t") == 0) {
UNONE::StrReplaceA(val, "0t");
return UNONE::StrToOctal64A(val);
}
if (val.find("0y") == 0) {
UNONE::StrReplaceA(val, "0y");
return UNONE::StrToBinary64A(val);
}
switch (radix) {
case 2: return UNONE::StrToBinary64A(val);
case 8: return UNONE::StrToOctal64A(val);
case 10: return UNONE::StrToDecimal64A(val);
case 16: return UNONE::StrToHex64A(val);
default: return UNONE::StrToHex64A(val);
}
}
std::wstring VariantFilePath(std::wstring path)
{
UNONE::StrReplaceIW(path, L"file:///");
return std::move(path);
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/cpp-wrapper/cpp-wrapper.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <functional>
// form: http://mindhacks.cn/2012/08/27/modern-cpp-practices/
class ScopeGuard
{
public:
explicit ScopeGuard(std::function<void()> onExitScope)
: onExitScope_(onExitScope), dismissed_(false) { }
~ScopeGuard()
{
if (!dismissed_)
{
onExitScope_();
}
}
void Dismiss()
{
dismissed_ = true;
}
private:
std::function<void()> onExitScope_;
bool dismissed_;
private: // noncopyable
ScopeGuard(ScopeGuard const&);
ScopeGuard& operator=(ScopeGuard const&);
};
#define SCOPEGUARD_LINENAME_CAT(name, line) name##line
#define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line)
#define ON_SCOPE_EXIT(callback) ScopeGuard SCOPEGUARD_LINENAME(EXIT, __LINE__)(callback)
int VariantInt(std::string val, int radix = 16);
int64_t VariantInt64(std::string val, int radix = 16);
std::wstring VariantFilePath(std::wstring path);
// disable logger, exit recover
#define DISABLE_RECOVER() \
UNONE::LogCallback routine;\
bool regok = UNONE::InterCurrentLogger(routine);\
if (regok) UNONE::InterRegisterLogger([&](const std::wstring &) {});\
ON_SCOPE_EXIT([&] {if (regok) UNONE::InterUnregisterLogger(); });
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/qt-wrapper/qt-wrapper.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "qt-wrapper.h"
#include "../common/common.h"
OpenArk *openark = nullptr;
QTranslator *app_tr = nullptr;
QApplication *app = nullptr;
QSize OpenArkTabStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const
{
QSize s = QProxyStyle::sizeFromContents(type, option, size, widget);
if (type == QStyle::CT_TabBarTab) {
s.transpose();
s.rwidth() = 140;
s.rheight() = 30;
}
return s;
}
void OpenArkTabStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
if (element == CE_TabBarTabLabel) {
const QStyleOptionTab* tabopt = reinterpret_cast<const QStyleOptionTab*>(option);
if (tabopt) {
QRect rect = tabopt->rect;
if (tabopt->state & QStyle::State_Selected) {
painter->save();
painter->setPen(0xb9b9b9);
painter->setBrush(QBrush(0xffffff));
if (tabopt->position != QStyleOptionTab::End) {
painter->drawRect(rect.adjusted(0, 0, 20, 0));
} else {
painter->drawRect(rect.adjusted(0, 0, 20, -1));
}
painter->restore();
painter->save();
painter->setPen(0x00868b);
QTextOption option;
option.setAlignment(Qt::AlignCenter);
QFont font = QFont("Microsoft YaHei", 11, QFont::Bold);
font.setPixelSize(15);
painter->setFont(font);
painter->drawText(rect, tabopt->text, option);
painter->restore();
} else {
painter->save();
painter->setPen(0xb9b9b9);
painter->setBrush(QBrush(0xf0f0f0));
if (tabopt->position != QStyleOptionTab::End) {
painter->drawRect(rect.adjusted(0, 0, 20, 0));
} else {
painter->drawRect(rect.adjusted(0, 0, 20, -1));
}
painter->restore();
painter->save();
QTextOption option;
option.setAlignment(Qt::AlignCenter);
QFont font = QFont("Microsoft YaHei", 11);
font.setPixelSize(15);
painter->setFont(font);
painter->drawText(rect, tabopt->text, option);
painter->restore();
}
return;
}
}
else if (element == CE_TabBarTab) {
QProxyStyle::drawControl(element, option, painter, widget);
}
}
OpenArkLanguage* OpenArkLanguage::langobj_ = nullptr;
OpenArkLanguage* OpenArkLanguage::Instance()
{
if (langobj_) return langobj_;
langobj_ = new OpenArkLanguage;
return langobj_;
}
void OpenArkLanguage::ChangeLanguage(int lang)
{
curlang_ = lang;
switch (lang) {
case -1:
if (QLocale::system().language() == QLocale::Chinese) {
return ChangeLanguage(1);
} else {
return ChangeLanguage(0);
}
break;
case 0:
if (app_tr) {
app->removeTranslator(app_tr);
//emit languageChaned();
}
break;
case 1:
if (app_tr) {
app_tr->load(":/OpenArk/lang/openark_zh.qm");
app->installTranslator(app_tr);
//emit languageChaned();
}
default:
break;
}
}
QIcon LoadIcon(QString file_path)
{
static struct {
QMutex lck;
QMap<QString, QIcon> d;
} icon_cache;
QMutexLocker locker(&icon_cache.lck);
if (icon_cache.d.contains(file_path)) {
auto it = icon_cache.d.find(file_path);
return it.value();
}
QFileInfo file_info(file_path);
QFileIconProvider provider;
QIcon &ico = provider.icon(file_info);
for (auto qs : ico.availableSizes()) {
if (!ico.pixmap(qs).isNull()) {
icon_cache.d.insert(file_path, ico);
return ico;
}
}
ico = QIcon(":/OpenArk/revtools/default.ico");
icon_cache.d.insert(file_path, ico);
return ico;
}
bool IsContainAction(QMenu *menu, QObject *obj)
{
QAction *action = qobject_cast<QAction*>(obj);
for (auto a : menu->actions()) {
if (action == a) {
return true;
}
}
return false;
}
bool ExploreFile(QString file_path)
{
QString cmdline = "explorer.exe /select," + file_path;
return UNONE::PsCreateProcessW(cmdline.toStdWString(), SW_SHOW, NULL);
}
QString GetItemModelData(QAbstractItemModel *model, int row, int column)
{
return model->data(model->index(row, column)).toString();
//auto idx = model->index(row, column);
//return idx.sibling(row, column).data().toString();
}
QString GetItemViewData(QAbstractItemView *view, int row, int column)
{
auto idx = view->rootIndex();
return idx.sibling(row, column).data().toString();
}
int GetCurViewRow(QAbstractItemView *view)
{
return view->currentIndex().row();
}
int GetCurViewColumn(QAbstractItemView *view)
{
return view->currentIndex().column();
}
QModelIndex GetCurItemView(QAbstractItemView *view, int column)
{
auto idx = view->currentIndex();
return idx.sibling(idx.row(), column);
}
QString GetCurItemViewData(QAbstractItemView *view, int column)
{
auto idx = view->currentIndex();
return idx.sibling(idx.row(), column).data().toString();
}
void SetCurItemViewData(QAbstractItemView *view, int column, QString val)
{
auto idx = view->currentIndex();
view->model()->setData(idx.sibling(idx.row(), column), val);
}
void ExpandTreeView(const QModelIndex& index, QTreeView* view)
{
if (!index.isValid()) {
return;
}
int childCount = index.model()->rowCount(index);
for (int i = 0; i < childCount; i++) {
const QModelIndex &child = index.child(i, 0);
ExpandTreeView(child, view);
}
if (!view->isExpanded(index)) {
view->expand(index);
}
}
void ClearItemModelData(QStandardItemModel* model, int pos)
{
model->removeRows(pos, model->rowCount());
}
QString MsToTime(LONGLONG ms)
{
return WStrToQ(UNONE::TmFormatMsW(ms, L"Y-M-D H:W:S", NULL));
}
void SetDefaultTableViewStyle(QTableView* view, QStandardItemModel* model)
{
view->setModel(model);
view->setSortingEnabled(true);
view->verticalHeader()->hide();
view->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
view->horizontalHeader()->setStretchLastSection(true);
view->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
view->horizontalHeader()->setMinimumSectionSize(100);
view->verticalHeader()->setDefaultSectionSize(25);
view->selectionModel()->selectedIndexes();
view->setEditTriggers(false);
}
void SetDefaultTreeViewStyle(QTreeView* view, QStandardItemModel* model)
{
view->setModel(model);
view->header()->setDefaultAlignment(Qt::AlignLeft);
//view->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
view->header()->setMinimumSectionSize(100);
view->setSortingEnabled(true);
}
void SetDefaultTreeViewStyle(QTreeView* view, QStandardItemModel* model,
QSortFilterProxyModel *proxy, std::vector<std::pair<int, QString>>& layout)
{
proxy->setSourceModel(model);
proxy->setDynamicSortFilter(true);
proxy->setFilterKeyColumn(1);
view->setModel(proxy);
view->selectionModel()->setModel(proxy);
view->header()->setSortIndicator(-1, Qt::AscendingOrder);
view->header()->setStretchLastSection(false);
view->setSortingEnabled(true);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
QStringList name_list;
for (int i = 0; i < layout.size(); i++) {
name_list << layout[i].second;
}
model->setHorizontalHeaderLabels(name_list);
for (int i = 0; i < layout.size(); i++) {
if (layout[i].first)
view->setColumnWidth(i, layout[i].first);
}
}
int GetLayoutIndex(std::vector<std::pair<int, QString>> &layout, QString name)
{
for (int i = 0; i < layout.size(); i++) {
if (layout[i].second == name) return i;
}
return 0;
}
void SetLineBgColor(QStandardItemModel *model, int row, const QBrush &abrush)
{
for (int i = 0; i < model->columnCount(); i++) {
model->item(row, i)->setBackground(abrush);
}
}
void SetLineHidden(QTreeView *view, int row, bool hide)
{
view->setRowHidden(row, view->rootIndex(), hide);
}
bool JsonParse(const QByteArray &data, QJsonObject &obj)
{
QJsonParseError err;
QJsonDocument doc;
doc = QJsonDocument::fromJson(data, &err);
if (err.error != QJsonParseError::NoError) {
return false;
}
if (!doc.isObject()) {
return false;
}
obj = doc.object();
return true;
}
bool JsonGetValue(const QJsonObject &obj, const QString &key, QJsonValue &val)
{
if (!obj.contains(key)) {
return false;
}
val = obj[key];
return true;
}
bool JsonGetValue(const QByteArray &data, const QString &key, QJsonValue &val)
{
QJsonObject obj;
if (!JsonParse(data, obj)) {
return false;
}
if (!JsonGetValue(obj, key, val)) {
return false;
}
return JsonGetValue(obj, key, val);
}
void ShellOpenUrl(QString url)
{
ShellExecuteW(NULL, L"open", url.toStdWString().c_str(), NULL, NULL, SW_SHOW);
}
void ShellRun(QString cmdline, QString param)
{
ShellExecuteW(NULL, L"open", cmdline.toStdWString().c_str(), param.toStdWString().c_str(), NULL, SW_SHOW);
}
void ShellRunHide(QString cmdline, QString param)
{
ShellExecuteW(NULL, L"open", cmdline.toStdWString().c_str(), param.toStdWString().c_str(), NULL, SW_HIDE);
}
void ShellRunCmdExe(QString exe, int show)
{
auto cmdline = "cmd /c " + exe;
UNONE::PsCreateProcessW(cmdline.toStdWString(), show);
}
void ShellRunCmdDir(QString dir)
{
auto cmdline = "cmd /k cd /D" + dir;
UNONE::PsCreateProcessW(cmdline.toStdWString());
}
QString PidFormat(DWORD pid)
{
if (pid == -1) return "N/A";
return QString("%1").arg(pid);
}
QString NameFormat(QString name)
{
return name.replace(" *32", "");
} | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/qt-wrapper/qt-wrapper.h | C/C++ Header | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#pragma once
#include <unone.h>
#include <Windows.h>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
#include <QIcon>
#include <QPainter>
#include <QProxyStyle>
#include <QSize>
#include <QTreeView>
#include <QModelIndex>
#include <QStandardItem>
#include <QAbstractItemView>
#include <QMessageBox>
#include <QPoint>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <openark/openark.h>
extern QTranslator *app_tr;
extern OpenArk *openark;
extern QApplication *app;
class OpenArkTabStyle : public QProxyStyle {
public:
QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const;
void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const;
};
// Language
#include <qtranslator.h>
class OpenArkLanguage : public QObject {
Q_OBJECT
public:
OpenArkLanguage() { curlang_ = -1; };
~OpenArkLanguage() {};
public:
static OpenArkLanguage* Instance();
void ChangeLanguage(int lang);
int GetLanguage() { return curlang_; };
signals:
void languageChaned();
private:
static OpenArkLanguage *langobj_;
int curlang_;
};
#define PROXY_FILTER(classname) \
class classname : public QSortFilterProxyModel {\
Q_OBJECT \
public: \
classname(QWidget *parent) {};\
~classname() {}; \
protected: \
bool lessThan(const QModelIndex &left, const QModelIndex &right) const; \
};
#define TR(str) QObject::tr(str)
#define TRA(str) QObject::tr(str).toStdString().c_str()
#define TRW(str) QObject::tr(str).toStdWString().c_str()
#define QToChars(qstr) qstr.toStdString().c_str()
#define QToWChars(qstr) qstr.toStdWString().c_str()
#define QToStr(qstr) qstr.toStdString()
#define QToWStr(qstr) qstr.toStdWString()
#define QDecToDWord(qstr) UNONE::StrToDecimalW(qstr.toStdWString())
#define QHexToDWord(qstr) UNONE::StrToHexW(qstr.toStdWString())
#define QDecToQWord(qstr) UNONE::StrToDecimal64W(qstr.toStdWString())
#define QHexToQWord(qstr) UNONE::StrToHex64W(qstr.toStdWString())
#define CharsToQ(chars) QString::fromLocal8Bit(chars)
#define WCharsToQ(wchars) QString::fromWCharArray(wchars)
#define StrToQ(str) QString::fromStdString(str)
#define WStrToQ(wstr) QString::fromStdWString(wstr)
#define ByteToHexQ(w) StrToQ(UNONE::StrFormatA("%02X", w))
#define WordToHexQ(w) StrToQ(UNONE::StrFormatA("%04X", w))
#define DWordToDecQ(w) StrToQ(UNONE::StrFormatA("%d", w))
#define DWordToHexQ(w) StrToQ(UNONE::StrFormatA("%08X", w))
#define QWordToDecQ(w) StrToQ(UNONE::StrFormatA("%lld", w))
#define QWordToHexQ(w) StrToQ(UNONE::StrFormatA("%016llX", w))
inline void MsgBoxInfo(QString msg)
{
QMessageBox::information(nullptr, QObject::tr("OpenArk Information"), msg);
}
inline void MsgBoxWarn(QString msg)
{
QMessageBox::warning(nullptr, QObject::tr("OpenArk Warning"), msg);
}
inline void MsgBoxError(QString msg)
{
QMessageBox::critical(nullptr, QObject::tr("OpenArk Error"), msg);
}
inline void LabelSuccess(QLabel* label, QString msg)
{
label->setText(msg);
label->setStyleSheet("color:green");
}
inline void LabelError(QLabel* label, QString msg)
{
label->setText(msg);
label->setStyleSheet("color:red");
}
inline QStringList VectorToQList(const std::vector<std::string>& vec)
{
QStringList result;
for (auto& s : vec) {
result.append(StrToQ(s));
}
return result;
};
inline QStringList WVectorToQList(const std::vector<std::wstring>& vec)
{
QStringList result;
for (auto& s : vec) {
result.append(WStrToQ(s));
}
return result;
};
inline std::vector<std::string> QListToVector(const QStringList& lst)
{
std::vector<std::string> result;
for (auto& s : lst) {
result.push_back(s.toStdString());
}
return result;
};
inline std::vector<std::wstring> QListToWVector(const QStringList& lst)
{
std::vector<std::wstring> result;
for (auto& s : lst) {
result.push_back(s.toStdWString());
}
return result;
};
__inline QString ByteArrayToHexQ(BYTE* arr, int len) {
std::string str = UNONE::StrStreamToHexStrA(std::string((char*)arr, len));
str = UNONE::StrInsertA(str, 2, " ");
return StrToQ(str);
};
__inline QString WordArrayToHexQ(WORD* arr, int len) {
std::string str = UNONE::StrStreamToHexStrA(std::string((char*)arr, len * 2));
str = UNONE::StrInsertA(str, 4, " ");
return StrToQ(str);
};
#define AppendTreeItem(root, name, value) \
item = new QStandardItem(name); \
root->appendRow(item); \
root->setChild(row++, 1, new QStandardItem(value));
#define InitTableItem(root) \
int column = 0;\
int count = root->rowCount();\
QStandardItem *item;\
#define InitTableItem2(root, cnt) \
int column = 0;\
count = cnt;\
QStandardItem *item;\
#define AppendTableItem(root, value) \
item = new QStandardItem(value);\
root->setItem(count, column++, item);
#define AppendTableIconItem(root, ico, value) \
item = new QStandardItem(ico, value);\
root->setItem(count, column++, item);
#define AppendNameValue(root, name, value) \
root->setItem(count, 0, new QStandardItem(name)); \
root->setItem(count, 1, new QStandardItem(value)); \
count++
#define AppendTableRowNameVaule(root, name, value) \
count = root->rowCount();\
root->setItem(count, 0, new QStandardItem(name)); \
root->setItem(count, 1, new QStandardItem(value)); \
// MVC wrapper
QModelIndex GetCurItemView(QAbstractItemView *view, int column);
QString GetItemModelData(QAbstractItemModel *model, int row, int column);
QString GetItemViewData(QAbstractItemView *view, int row, int column);
QString GetCurItemViewData(QAbstractItemView *view, int column);
void SetCurItemViewData(QAbstractItemView *view, int column, QString val);
int GetCurViewRow(QAbstractItemView *view);
int GetCurViewColumn(QAbstractItemView *view);
void ClearItemModelData(QStandardItemModel* model, int pos = 0);
void ExpandTreeView(const QModelIndex& index, QTreeView* view);
void SetDefaultTableViewStyle(QTableView* view, QStandardItemModel* model);
void SetDefaultTreeViewStyle(QTreeView* view, QStandardItemModel* model);
void SetDefaultTreeViewStyle(QTreeView* view, QStandardItemModel* model, QSortFilterProxyModel *proxy,
std::vector<std::pair<int, QString>>& layout);
int GetLayoutIndex(std::vector<std::pair<int, QString>> &layout, QString name);
#define LAYOUT_INDEX(str) GetLayoutIndex(layout, tr(str))
void SetLineBgColor(QStandardItemModel *model, int row, const QBrush &abrush);
void SetLineHidden(QTreeView *view, int row, bool hide);
// Others
QIcon LoadIcon(QString file_path);
bool IsContainAction(QMenu *menu, QObject *obj);
bool ExploreFile(QString file_path);
QString MsToTime(LONGLONG ms);
// Json
bool JsonParse(const QByteArray &data, QJsonObject &obj);
bool JsonGetValue(const QJsonObject &obj, const QString &key, QJsonValue &val);
bool JsonGetValue(const QByteArray &data, const QString &key, QJsonValue &val);
//
void ShellOpenUrl(QString url);
void ShellRun(QString cmdline, QString param);
void ShellRunHide(QString cmdline, QString param);
void ShellRunCmdExe(QString exe, int show = SW_SHOW);
void ShellRunCmdDir(QString dir);
QString PidFormat(DWORD pid);
QString NameFormat(QString name);
| wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong | ||
src/OpenArk/common/ui-wrapper/ui-wrapper.cpp | C++ | /****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "ui-wrapper.h" | wsdjeg/OpenArk-backup | 0 | C++ | wsdjeg | Eric Wong |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.